Java NIO Serversocketchannel
A Java NIO Serversocketchannel is a channel this can listen for incoming TCP connections, just as a in standard ServerSocket Ja VA Networking. The ServerSocketChannel class is located java.nio.channels .
Here are an example:
Serversocketchannel Serversocketchannel = serversocketchannel.open (); Serversocketchannel.socket (). Bind ( New Inetsocketaddress (9999)); while (true) { = serversocketchannel.accept (); // Do something with Socketchannel...}
Opening a Serversocketchannel
You open a by ServerSocketChannel calling the ServerSocketChannel.open() method. Here's how this looks:
Serversocketchannel Serversocketchannel = Serversocketchannel.open ();
Closing a Serversocketchannel
Closing A is do by ServerSocketChannel calling the ServerSocketChannel.close() method. Here's how this looks:
Serversocketchannel.close ();
Listening for Incoming Connections
Listening for incoming connections was done by calling the ServerSocketChannel.accept() method. When accept() the method is returns, it returns a with an SocketChannel incoming connection. Thus, the accept() method blocks until an incoming connection arrives.
Since you is typically not interested in listening just for a single connection, you call the accept() inside a while-loop. Here's how this looks:
while (true) { = serversocketchannel.accept (); // Do something with Socketchannel...}
Of course you would use some other stop-criteria than true inside the while-loop.
Non-blocking Mode
A ServerSocketChannel can is set into non-blocking mode. In non-blocking mode accept() the method returns immediately, and may thus return NULL, if no incoming connection had arrive D. Therefore you'll have a to check if the returned is SocketChannel null. Here are an example:
Serversocketchannel Serversocketchannel = serversocketchannel.open (); Serversocketchannel.socket (). Bind ( New Inetsocketaddress (9999)); Serversocketchannel.configureblocking (false); while (true) { = serversocketchannel.accept (); if NULL ) { //dosomething with Socketchannel ... }}
Java NIO (9) Serversocketchannel