My ServerSocket (java.net.ServerSocket) only flushes the data if I close the OutputStream, but if I close the OutputStream, it closes the connection. Here is my code
Server:
ServerSocket server = new ServerSocket(7788);
Socket client = server.accept();
OutputStream os = client.getOutputStream();
os.write("Hello World".getBytes());
os.flush();
// os.close();
Client:
Socket client = new Socket("localhost", 7788);
byte[] bytes = client.getInputStream().readAllBytes();
String message = new String(bytes);
System.out.println(message);
If I close the OutputStream everything works fine, but I need to send data multiple times for my project. Is there a solution for this?
the problem is not the
flush()on theOutputStream(server), but rather thereadAllBytes()on theInputStream(client). from the docs (emphasis mine):end of streamis "sent" only onclose(), that is why you are able to read (print) the message only afterclose().a very simple solution to exchange one-line textual data would be to send messages separated by '\n' (new line) character and on the client part, read from the socket line-by-line, for example:
Server.javaClient.javaif you run the above code, you will see that messages gets printed (received) one after the other with a 2 seconds delay and
readLine()returns as soon as it read a\n(new line) character.if this is not feasible for your use case, I think you will need a more structured protocol.