Server Socket在Java中无限期地读取客户端消息

时间:2017-12-13 10:48:58

标签: java sockets client-server datainputstream dataoutputstream

在我的简单Java Client-Server程序中,当向服务器发送消息并在那里读取消息时,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);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

它永远不会阅读的原因是因为没有发送任何内容,正如xander所说的那样。 这是我的错,我没有包含实际的客户端代码,只包括服务器代码和最小化的客户端代码版本。

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

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