简体   繁体   中英

Read server response using Java Sockets API

I have created a simple class which sends a string to a server, both communicate using Java Sockets API. The server reads what the client have sent, and responds with another string. But the client can not read that response.

This is the client class:

import java.io.IOException;
import java.net.Socket;

public class Client {

    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("localhost", 8181);
        socket.getOutputStream().write("Hello".getBytes());

        int read;
        while ((read = socket.getInputStream().read()) > -1) {
            System.out.print((char) read);
        }

        socket.close();
    }

}

And this is the server class:

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8181);

        while (true) {
            Socket socket = serverSocket.accept();
            int read;
            while ((read = socket.getInputStream().read()) > -1) {
                System.out.print((char) read);
            }

            socket.getOutputStream().write("Hi!".getBytes());
        }

    }

}

I imagine that the problem may be in the client execution flow, because I don`t know how canI do it wait for a server response. In other words, how to implement a client able to read the server response?

  1. You aren't closing the sockets.
  2. The server is attempting to read until end of stream and then send a reply. End of stream only happens when the peer closes the connection, so it won't be possible to send a reply even after you fix (1). You need to read a message, whatever that means in your application protocol.

您需要刷新或关闭输出流。

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