I have a project in which i make a chat server, where people(client) connect and choose a partner to chat with. However, they chat only when both clients send a message they see what the other typed. What I want is something like Whatsapp where we send many messages one after the other without waiting for the other client to send.
I tried to create a thread class where I invoke the chat and other stuff, but never worked.
//this is the client.java and this is the part of the code where they start chatting
do {
System.out.print(dis.readUTF());
System.out.println(dis.readUTF());
send = in.next();
dos.writeUTF(send);
b = dis.readBoolean();
} while (b);
//this is part of the chatserver.java where the connection is done they start chatting
class handleClient implements Runnable {
private Socket s1;
private Socket s2;
private String name1;
private String name2;
public handleClient(Socket s1, Socket s2, String n1, String n2) {
this.s1 = s1;
this.s2 = s2;
this.name1 = n1;
this.name2 = n2;
}
@Override
public void run() {
String msg1 = "", msg2 = "";
boolean b;
try {
DataOutputStream dos1 = new DataOutputStream(s1.getOutputStream());
DataInputStream dis1 = new DataInputStream(s1.getInputStream());
DataOutputStream dos2 = new DataOutputStream(s2.getOutputStream());
DataInputStream dis2 = new DataInputStream(s2.getInputStream());
do {
dos1.writeUTF(name1 + ": ");
dos2.writeUTF(name2 + ": ");
dos2.writeUTF(name1 + ": " + msg1);
msg1 = dis1.readUTF();
dos1.writeUTF(name2 + ": " + msg2);
msg2 = dis2.readUTF();
b = !msg1.equals(name1 + " is out") && !msg2.equals(name2 + " is out");
dos1.writeBoolean(b);
dos2.writeBoolean(b);
} while (b);
dos1.close();
dis1.close();
dos2.close();
dis2.close();
s1.close();
s2.close();
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
}