简体   繁体   中英

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. 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. I would like to close the socket when the count is -1, but i am not successful. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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