简体   繁体   English

无法从套接字读取中捕获-1响应

[英]not able to catch -1 response from socket read

I have a class that serves as a client thread. 我有一个充当客户端线程的类。 in the class i have a run method that deals with the reading and writing operations from and to the socket. 在该类中,我有一个run方法,该方法处理套接字的读写操作。 my run method looks like this: 我的运行方法如下所示:

public void run(){
    System.out.println("New connection at " + new Date() + "\n");
    try {
        DataInputStream in = new DataInputStream (threadSocket.getInputStream());
        out = new DataOutputStream (threadSocket.getOutputStream());                  
        while (running){
            // read input from client
            byte[] input = new byte [200];
            int count = in.read(input);
            if (count == -1) {
                running = false;
                break;
            }

            String msg = new String(input, 0, count);

            // parse in going message
            messageParsing(msg);

            // respond to client
            response();  
        }
    } 
    catch (IOException ex) {ex.printStackTrace();}
    finally {
        try {
            threadSocket.close();
            System.out.println("Connection closed.\n");
        } catch (IOException ex) {ex.printStackTrace();}
    }
}

I have created a fixed size byte array and i am reading the data from the socket into it. 我创建了一个固定大小的字节数组,并且正在从套接字读取数据。 The available lengths of the data coming in are 147 and 61, if the length of the input data is 0 it does not mean any thing. 输入的数据的可用长度为147和61,如果输入数据的长度为0,则没有任何意义。 I would like to close the socket when the count is -1, but i am not successful. 我想在计数为-1时关闭套接字,但我不成功。 It seems like when the there is no data, count is 0 it just keeps trying to read data from the socket and it gets stuck. 似乎当没有数据时,count为0时,它只是一直试图从套接字读取数据而被卡住。

How can i fix this problem? 我该如何解决这个问题? What am i doing wrong? 我究竟做错了什么? Any help would be appreciated. 任何帮助,将不胜感激。

当另一通信侧实际上已关闭其输出时,流只能返回-1,即用信号通知结束,从而确保不再传输任何数据。

Cannot reproduce. 无法复制。 Your code can never get zero from a read. 您的代码永远不会从读取中获得零。 If you aren't getting -1 it is because the peer never closes the connection. 如果您没有得到-1,那是因为对等方永远不会关闭连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM