服务器套接字在 Java 中无限期地读取客户端消息

Server Socket reads Client message indefinitely in Java

在我简单的 Java 客户端-服务器程序中,当向服务器发送消息并在那里读取时,readInt() 无限期地读取,使程序停留在那里。

我确保我只是发送和接收一个 int,没有别的,正如你可以从代码中看出的那样(我也尝试过在发送的消息中添加和不添加 \n 以查看它是否会结束):

相关客户代码

Socket server = new Socket("127.0.0.1", 2424);
DataOutputStream outputStream = new DataOutputStream(server.getOutputStream());
DataInputStream inputStream = new DataInputStream(server.getInputStream());
outputStream.writeInt(Protocol.Message.HANDSHAKE);
outputStream.write('\n'); // I tried with and without this
outputStream.flush();

相关服务器代码

ServerSocket socket = new ServerSocket(2424);
System.out.println("Listening on port 2424");

while (connected) {
    Socket client = socket.accept();
    System.out.println("SERVER: Going to read a message"); // This shows
    int messageType = (new DataInputStream(client.getInputStream())).readInt();
    System.out.println("SERVER: Received a message (" + messageType + ")"); // This does not
    commands.execute(messageType);
}

应该在readInt() 之后打印的消息从未见过。我以为会,因为我只发送一个 int 并接收一个 int(4 字节),这不像我发送的数据比预期的多。

我应该如何结束 readInt()?我是否必须发送空字节或其他内容?

编辑:实际服务器代码(使用线程)。

ServerSocket socket = new ServerSocket(2424);
System.out.println("Listening on port 2424");

while (connected) {
    Socket client = socket.accept();
    Worker worker = new Worker(client);
    worker.start();
}

工作线程

public class Worker extends Thread {
    private final Socket client;
    private final Commands commands;

    private final DataOutputStream outputStream;
    private final DataInputStream inputStream;

    public Worker(Socket client) throws IOException {
        System.out.println("SERVER: Handling client message");
        this.client = client;

        outputStream = new DataOutputStream(client.getOutputStream());
        inputStream = new DataInputStream(client.getInputStream());

        commands = new Commands();
        commands.addCommand(Protocol.Message.HANDSHAKE, new HandshakeCommand());
        //commands.addCommand(Protocol.Message.RECEIVE_FILE, new ReceiveFileCommand());
    }

    @Override
    public void run() {
        System.out.println("SERVER: Running thread for client message");
        try {
            int messageType = inputStream.readInt();

            System.out.println("SERVER: Received a message (ID " + messageType + ")");
            commands.execute(messageType);
        } catch (IOException | UnknownCommandException ex) {
            System.out.println(ex);
        }
    }
}

xander 所说,它从未读取的原因是因为没有发送任何内容。 这是我的错,我没有包括实际的客户端代码,只有服务器代码和客户端代码的最小化版本。

我试图在客户端的 while() 循环之后发送消息(它还等待来自服务器的消息)。

解决方案是将客户端的监听部分委托给另一个线程,这样它就不会阻塞需要将消息发送到服务器的主线程。