繁体   English   中英

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

[英]how to close a running socket 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);}
        }
    }}

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

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

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

注意您对available()使用也是错误的。 只需读入固定大小的缓冲区即可。

您可以大大简化代码。

暂无
暂无

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

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