简体   繁体   English

如何在Java中关闭ServerSocket.accept()命令?

[英]How to close the ServerSocket.accept() command in java?

My problem is that the ServerSocket.accept() command keeps waiting until a client has connected to it. 我的问题是ServerSocket.accept()命令一直等待,直到客户端已连接到它为止。 But what I want to do is that I have to listen for a client for a few seconds. 但是我想做的是我必须听客户几秒钟。 If a client connects, then I send data to the client otherwise I have to terminate the ServerSocket. 如果客户端连接,则我将数据发送到客户端,否则必须终止ServerSocket。

So how do I bypass the ServerSocket.accept() command when no client has connected for some time? 那么当一段时间没有客户端连接时,如何绕过ServerSocket.accept()命令?

Call ServerSocket.close() (from another thread of course). 调用ServerSocket.close() (当然是从另一个线程调用)。 SocketException will be thrown for any thread blocking on accept() , but if a connection has been made, then existing Socket is still fine. 对于任何在accept()上阻塞的线程,都会抛出SocketException ,但是如果建立了连接,则现有的Socket仍然可以。

A simple and naive example 一个简单而天真的例子

    ServerSocket ss = new ServerSocket(8123);

    new Thread() {
        @Override
        public void run() {
            try {
                Thread.sleep(5000);
                ss.close();
            } catch(InterruptedException e) {
            } catch(IOException e) {
            }
        }
    }.start();
    Socket s = ss.accept();

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

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