为什么服务器停止接收来自客户端的新行?

问题描述 投票:0回答:0

我正在学习 Java 套接字编程,并且在服务器的无限循环中从客户端套接字输出输入时遇到了困难。我做错了什么导致服务器从客户端打印一行然后停止?

服务器:

public class TestServer {
    private int port;
    private ServerSocket socket;
    private Socket clientSocket;

    public TestServer(int p) throws IOException {
        port = p;
        socket = new ServerSocket(port);
        out.println("service listening on port " + socket.getLocalPort());

        DataInputStream dis = null;
        while(true) {
            clientSocket = socket.accept();
            out.println("client connected: " + clientSocket.getInetAddress().getHostAddress() + ":" + clientSocket.getPort());
            dis = new DataInputStream(clientSocket.getInputStream());

            String read = dis.readUTF();
                out.println(clientSocket.getInetAddress().getHostAddress() +
                        ":" + clientSocket.getPort() + "\t\t`" + read.trim() + "`");
        }


    }

    public static void main(String[] args) throws IOException {
        new TestServer(8000);
    }
}

客户:

public class TestClient {
    private final int port;
    private final String host;
    private final Socket socket;

    public TestClient(String h, int p) throws IOException {
        port = p;
        host = h;

        socket = new Socket(host, port);

        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());

        int i = 0;
        while(i<10) {
            dos.writeUTF("hi " + i);
            dos.flush();
            i++;
        }

        dos.close();
    }

    public static void main(String[] args) throws IOException {
        new TestClient("127.0.0.1", 8000);
    }
}

先运行服务器,然后运行客户端,客户端连接,向服务器发送一行,服务器接受并打印到其控制台,但在第一次迭代后停止。期望客户端的更多行被打印到服务器实例的控制台。

java sockets networking blocking
© www.soinside.com 2019 - 2024. All rights reserved.