I am trying to make a simple chat application using Java sockets, here is the code for the server:
public ServerSocket ss;
public ArrayList<Client> Clients = new ArrayList<Client>();
String Alphabets = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789";
public Server() throws IOException
{
ss = new ServerSocket(1111);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(null);
this.setResizable(false);
this.setSize(400,150);
this.getContentPane().setBackground(Color.BLACK);
this.setTitle("Server");
JLabel label = new JLabel("Server Running");
label.setForeground(Color.WHITE);
label.setBounds(15,25,350,60);
label.setFont(new Font(Font.SANS_SERIF,Font.PLAIN,50));
this.add(label);
this.setVisible(true);
while(true)
{
Socket socket = ss.accept();
DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
String id = getId();
dout.writeUTF(id);
Client c = new Client(socket,id);
dout.close();
dout.flush();
}
}
String getId()
{
Random rand = new Random();
String id = "";
for(int i = 0;i < 6;i )
{
char i3 = Alphabets.charAt(rand.nextInt(0,Alphabets.length()));
id = i3;
}
return id;
}
everything works fine, when the client connects he gets an id and is added to Clients
here is the code for the client connection:
public String Connect() throws UnknownHostException, IOException
{
mySocket = new Socket("localhost",1111);
DataInputStream din = new DataInputStream(mySocket.getInputStream());
String id = din.readUTF();
return id;
}
the problem is I get the exception java.net.SocketException: An established connection was aborted by the software in your host machine as I send input to the server, it doesn't send the first time I press send, and the next time I press send it give this exception, here is the code for sending input:
public void SendMessage(String msg) throws IOException
{
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
dout.writeUTF(msg);
AddToMessages(Id ": " msg);
}
I'd be really glad if someone helps as I have been researching this problem for a long time and no one have seemed to come up to it.
CodePudding user response:
Well I found out that restarting your pc solves the problem, this is kinda weird but it works!