I am implementing a server using Java ServerSocket and have two clients connecting, each from different threads. One sends a message to the server and one reads a message from the server. They both contact the server on the same port, so how do I differentiate between a client that wants to read and one that wants to write?
ServerSocket ss = new ServerSocket(port);
while (true) {
Socket cs = ss.accept();
BufferedReader r = new BufferedReader(new InputStreamReader(cs.getInputStream()));
String message = r.readLine();
System.out.println("message");
DataOutputStream os = new DataOutputStream(cs.getOutputStream());
String send = "send";
os.writeBytes(send);
}
The last writeBytes causes problems since a client that connected in order to send a message to the server has already closed the connection. Similarly, a client that wants to receive from the server isn’t going to submit anything on the socket’s input stream
You will have to make the client write a byte or a String after opening the session indicating if it wants to read or write, you can’t really do this magically if they connect to the same port, unless you could differentiate them by ip address or something