I have two classes- a client and a server. Both are able to read and write Strings, which are read via scanner class, until a specific String ("end") is typed, prompting the server to close the socket. However, I am unable to send multiple messages one after another and make them appear in the client's console, because the loop, which checks for the "end" string basically requires me to send one message before I can read the next one (hopefully that makes sense)
Example:
Server Console
(sent messages first)
hello //Output
hello //Output
hello //Input
hello //Input
hello //Input
Client Console
hello //Output
hello //Input
hello //Output
hello //Input
hello //Output
Hopefully it makes sense how the timing/order of the sent messages is off. Instead of two messages appearing one after another, one appears first and I then have to send one before the second one comes up.
Any help greatly appreciated!
Source code for the client:
import java.io.*;
import java.net.*;
public class client {
public static void main(String[] args) {
try {
Socket socket = new Socket("127.0.0.1",1201);
DataInputStream dInputStream = new DataInputStream(socket.getInputStream());
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
String msgin="",msgoutString="";
while (!msgin.equals("end")) {
msgoutString=bReader.readLine();
dataOutputStream.writeUTF(msgoutString);
msgin=dInputStream.readUTF();
System.out.println(msgin);
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
Source code for the server:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Timer;
public class server {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(1201);
Socket s = ss.accept();
DataInputStream dInputStream = new DataInputStream(s.getInputStream());
DataOutputStream dataOutputStream = new DataOutputStream(s.getOutputStream());
BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
String msgin="",msgoutString="";
while (!msgin.equals("end")) {
msgin=dInputStream.readUTF();
System.out.println(msgin);
msgoutString=bReader.readLine();
dataOutputStream.writeUTF(msgoutString);
dataOutputStream.flush();
}
s.close();
} catch (Exception e) {
// TODO: handle exception
}
}
}