My problem is that the ServerSocket.accept() command keeps waiting until a client has connected to it. 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.
So how do I bypass the ServerSocket.accept() command when no client has connected for some time?
Call ServerSocket.close()
(from another thread of course). SocketException
will be thrown for any thread blocking on accept()
, but if a connection has been made, then existing Socket
is still fine.
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();
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.