0

如何停止正在侦听客户端的服务器套接字。我的代码如下所示

 private ServerSocket serverSocket;

class ServerThread implements Runnable {

    private BufferedReader input;
    public void run() {
    Socket socket = null;

        try {
            serverSocket = new ServerSocket(SERVE_LISTEN_RPORT);
        } catch (IOException e) {
            e.printStackTrace();
        }

        while (!Thread.currentThread().isInterrupted()) {

            try {

                socket = serverSocket.accept();
                try {

        this.input = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                } catch (IOException e) {
                    e.printStackTrace();
                }

                try {
                     String read = input.readLine();
                                 //Do something
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }


             try {
              serverSocket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

    }
}

当我从另一个线程收到命令时,我需要停止这个线程。我已经提出了这个问题,但不知道如何实施。

4

2 回答 2

2

这是一个如何从其他线程关闭套接字的示例:

private static volatile ServerSocket serverSocket;

public static void main(String[] args) throws InterruptedException, IOException {
    Thread serverThread = new Thread(new ServerThread());
    serverThread.start();
    Thread.sleep(1000); // wait a  bit, then close
    serverSocket.close();
}

static class ServerThread implements Runnable {

    private BufferedReader input;

    public void run() {
        try {
            serverSocket = new ServerSocket(25);
            while (true) {
                Socket socket = serverSocket.accept();
                // client request handling logic
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
于 2013-08-31T10:14:37.767 回答
1

服务器套接字应该在run()方法之外并且应该由线程共享

现在,当您需要中断正在调用socket.accept()的线程时,另一个线程可以调用socket.close()accept()抛出异常。

于 2013-08-31T10:11:14.960 回答