I've two clients on two different machines and I don't know when they're gonna send requests.
is this the scenario where I HAVE TO use Selector
and ServerSocketChannel
?
Example:
public class Server{
public static void main(String[] args) {
try(
ServerSocket serverSocket = new ServerSocket(1234)
){
while(true) {
serverSocket.accept();
Thread.sleep(5*1000);
//and while its sleeping, second client sends request
}
}catch(Exception e){}
}
}
is this the scenario where I HAVE TO use Selector and ServerSocketChannel?
Nope. A more common solution is to have one thread per client - when you accept a call, create a new thread (or use an existing one from a thread-pool) and use that to handle that connection. The original thread calls accept
again (immediately - no sleep required) and spawns a new thread for the next connection, etc.
(There are certainly advantages to asynchronous IO, but you're not forced to use it.)
You dont have to use Selector
/ ServerSocketChannel
. Instead for a very simple server - you could simply start a new thread to handle the client connection. See Supporting Multiple Clients for an example on how to do this with a new thread per client.
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.