Java sockets: request-response template with object flows

My goal is to implement a simple Java socket-based request-response template that is used to request an object from the server.

It should work as follows:

  • The client sends a message to the server on which the server is evaluating. Depending on what he got a certain function. This part works.
  • The server writes the requested data to an ObjectOutputStream. This also works, at least I did not receive an error message.
  • The client reads data from the input stream until it receives a CLOSE message, which makes the program end the while loop. It does not work as it should.

Here are some pieces of critical code:

// Client (Sending request) *** WORKS objectOutputStream.writeInt(GET_OBJECT); objectOutputStream.flush(); // Server (After receipt of the message) *** WORKS objectOutputStream.writeInt(object); objectOutputStream.writeInt(CLOSE); // Client (Reading the answer from the server) *** WRONG while(true){ int i = objectInputStream.readInt(); if(i == CLOSE) break; } 
+4
source share
1 answer
  • You have flush on the client side and the message is received by the server;
  • you are missing flush on the server side and the message will not be received by the client.

I notice a pattern in these two facts ...

+2
source

Source: https://habr.com/ru/post/1483440/


All Articles