简体   繁体   中英

how to close a running socket thread?

I am running a server that enables multiple socket connections. i am trying to shut down the thread when the client side terminated the connection.

this is the code for the client thread:

class ClientThread implements Runnable {
    Socket threadSocket;
    private boolean chk = false, stop = false, sendchk = false, running = true;
    DataOutputStream out = null;

    //This constructor will be passed the socket
    public ClientThread(Socket socket){
        threadSocket = socket;
    }

    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
                int ln = in.available();
                byte [] bytes  = new byte [ln];
                in.read(bytes);
                String msg = new String(bytes);

                // parse in going message
                messageParsing(msg);

                // respond to client
                response();

                /////////////////////////////
                ////// this is the part that i thought would help me close the thread
                ////////////////////////////
                if (threadSocket.isInputShutdown()){
                    running = false;
                }
            }
        } 
        catch (IOException ex) {System.out.println(ex);}
        finally {
            try {
                threadSocket.close();
                System.out.println("Connection closed due to unauthorized entry.\n");
            } catch (IOException ex) {System.out.println(ex);}
        }
    }}

However, the if statement does not do the trick. The thread is still running and tries to send/read data from the socket. How can make it work? what am i missing? any help would be appreciated. thank you.

isInputShutdown() tells you whether you have shutdown the input of this socket. It doesn't have anything to do with the peer.

Your problem is that you are ignoring the result of the read() method. If it returns -1, the peer has closed the connection.

NB Your use of available() is also incorrect. Just read into a fixed sized buffer.

You can greatly simplify your code.

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