简体   繁体   中英

Java socket write immediately after read

Basically, what I want to achieve is to complete a ping-pang communication between a client socket and server socket.

The scenario should be like this:

  1. Client establishes the connection to server.
  2. Client sends "Hello" to server (via OutputStream), then start to read from server (via InputStream)
  3. Server reads "Hello" message and print to console, then sends "Hello" to client (via OutputSteam).
  4. Client prints the response message from server and exit.

Server Socket :

try (ServerSocket serverSocket = new ServerSocket(8080)) {
            while (true) {
                // Blocking here
                Socket socket = serverSocket.accept();
                InputStream inStream = socket.getInputStream();
                OutputStream outStream = socket.getOutputStream();

                String reqMessage = new String(inStream.readAllBytes(), StandardCharsets.UTF_8);
                System.out.println(reqMessage);

                String resMessage = "Hello";
                outStream.write(resMessage.getBytes(StandardCharsets.UTF_8));
                outStream.flush();
                System.out.println(String.format("Message '%s' has been sent to client", resMessage));

                outStream.close();
                socket.close();
            }
        }

Client socket:

Socket socket = new Socket("localhost", 8080);

        OutputStream outStream = socket.getOutputStream();
        outStream.write("Hello Server".getBytes(StandardCharsets.UTF_8));
        outStream.flush();

        InputStream inStream = socket.getInputStream();
        System.out.println("Received from server");
        System.out.println(new String(inStream.readAllBytes(), StandardCharsets.UTF_8));

        outStream.close();
        socket.close();

My problem:

Once the connection is established, both sides are blocked, no one is printing the proper message, just like they are waiting for each other. Once I shutdown the client, then the server prints all proper info. But if I removed the 'reading from server' part which is the InputStream part from client side, then both sides are working properly. I just got confused, why does it behave like this? if I want to make it work, what should I modify?

Thanks.

Your problem is with readAllBytes() . It doesn't mean it reads all bytes that are available, it reads all bytes until the stream is closed .

String reqMessage = new String(inStream.readAllBytes(), StandardCharsets.UTF_8);

will block until you close the client, because the server is still waiting for "all" the bytes. At the same time the client is waiting for the server to send something, which it of course can't do as it's still waiting for more data from the client.

You shouldn't be using bytes anyway, since you're writing text messages. Use BufferedReader with InputStreamReader and for example PrintWriter with OutputStreamWriter to write text. Don't forget that readLine() needs a newline from the sender, and specify the character encoding in InputStreamReader and OutputStreamWriter .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM