套接字多线程编程 DataInputStream.available() = 0 而输出流正确写入

问题描述

我在客户端类中使用了套接字并尝试从服务器获取成功写入 DataOutputStream 的字符串。下面是示例代码

try(Socket socket = new Socket(ip,port);)
    {
        // Output and Input Stream
        DataInputStream input = new DataInputStream(socket.getInputStream());
        
        DataOutputStream output = new DataOutputStream(socket.getoutputStream());       
        
        //receive message from server
        while(true && input.available() > 0)
        {
            String message = input.readUTF();
            System.out.println(message);
            TextArea.setText(message);
        }
        
    } 
    catch (UnkNownHostException e)
    {
        e.printstacktrace();
    }
    catch (IOException e) 
    {
        e.printstacktrace();
    }

但是,当我的客户想要在 TextArea 中显示该消息时。看来 input.available()=0 所以它没有显示该消息。但是当我打印出消息字符串时,它是我想要的确切字符串真的很令人困惑。最后,我去掉了 while 语句,直接使用 TextArea.setText(message)显示该消息。 谁能帮我澄清一下?

解决方法

服务器期望什么协议?如果服务器首先期待某个请求(例如 HTTP),则您需要在期待输入流中发送的任何字节之前发送请求(input.available 为 0 的原因)。

参见此处的示例:https://www.infoworld.com/article/2853780/socket-programming-for-scalable-systems.html