A Java NIO Serversocketchannel is a channel this can listen for incoming TCP connections, just as a serversocket in Stan Dard Java Networking. The Serversocketchannel class is located in the Java.nio.channelspackage.
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 serversocketchannel by calling the Serversocketchannel.open () method. Here's how this looks:
Serversocketchannel Serversocketchannel = Serversocketchannel.open ();
Closing a Serversocketchannel
Closing a serversocketchannel is do by 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 the Accept () method is returns, it returns a Socketchannel with an 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-loo P. 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 be set into non-blocking mode. In non-blocking mode the Accept () method returns immediately, and may thus return NULL, if no incoming connection had Arri Ved. Therefore you'll have a to check if the returned Socketchannel is null. Here's an example:
serversocketchannel Serversocketchannel = Serversocketchannel.open (); Serversocketchannel.socket (). Bind ( new inetsocketaddress (9999 false while (true =< Span style= "COLOR: #000000" > serversocketchannel.accept (); if (socketchannel! = null // do something W ITH Socketchannel ... }}
Java NIO Serversocketchannel