如何关闭正在运行的套接字线程?

时间:2016-07-20 09:51:31

标签: java multithreading sockets serversocket

我正在运行一个启用多个套接字连接的服务器。 我试图在客户端终止连接时关闭线程。

这是客户端线程的代码:

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);}
        }
    }}

但是,if语句不起作用。线程仍在运行,并尝试从套接字发送/读取数据。 怎么能让它起作用?我错过了什么? 任何帮助,将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:0)

isInputShutdown()告诉您是否已关闭此套接字的输入。它与同伴没有任何关系。

您的问题是您忽略了read()方法的结果。如果它返回-1,则对等体已关闭连接。

注意您对available()的使用也不正确。只需读入固定大小的缓冲区。

您可以大大简化代码。

相关问题