Java socket可以让客户端无法读取数据

时间:2017-06-03 22:15:48

标签: java sockets

客户端发送消息,然后服务器接收消息并响应消息。我不知道为什么客户端无法读取响应。如果我删除客户端中的读取部分,服务器可以获取该消息。但是对于以下代码,没有任何作用。我也尝试了flush(),它仍然无法正常工作。

对于客户

public void run() {

    try (Socket echoSocket = new Socket(HOSTNAME, Integer.parseInt(PORTNUMBER));
            DataOutputStream dOut = new DataOutputStream(echoSocket.getOutputStream());
            DataInputStream dIn = new DataInputStream(echoSocket.getInputStream());
    ) {

        while (true) {


            command = UI.commandQueue.take()
            dOut.writeInt(Message.toByteArray(command).length);
            dOut.write(Message.toByteArray(command));


            int length;
            while((length = dIn.readInt()) != 0) {
            if (length > 0){
                byte[] messagebyte = new byte[length];
                dIn.readFully(messagebyte, 0, messagebyte.length);
                try {
                    msg = Message.fromByteArray(messagebyte);
                    testDisplay(msg);
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                testDisplay(msg);
            }
            }


        }

    }catch (UnknownHostException e) {
        UI.display("Don't know about host " + HOSTNAME);
    } catch (IOException e) {
        UI.display("Couldn't get I/O for the connection to " + HOSTNAME);
    }
}

对于服务器

public void run() {

    try (ServerSocket serverSocket = new ServerSocket(Integer.parseInt(PORT_NUMBER));
            Socket clientSocket = serverSocket.accept();

            DataOutputStream dOut = new DataOutputStream(clientSocket.getOutputStream());
            DataInputStream dIn = new DataInputStream(clientSocket.getInputStream());) {
        int length;
        while ((length = dIn.readInt()) != 0) {
            if (length > 0) {
                byte[] messagebyte = new byte[length];
                dIn.readFully(messagebyte, 0, messagebyte.length); // read the
                                                                // message
                Message msg;
                try {
                    msg = Message.fromByteArray(messagebyte);
                    testDisplay(msg);
                    dOut.writeInt(Message.toByteArray(msg).length);
                    dOut.write(Message.toByteArray(msg));
                    UI.display("ack sent");
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    UI.display(e.getMessage());
                }

            }
            }
    } catch (IOException e) {
        UI.display(
                "Exception caught when trying to listen on port " + PORT_NUMBER + " or listening for a connection");
        UI.display(e.getMessage());
    }

}

1 个答案:

答案 0 :(得分:0)

您的服务器每个请求都会回显一个响应,但您的客户端正在尝试为每个请求读取多个响应,它永远不会获取,因此它会阻止。