Java NiO's Serversocketchannel is the channel used to listen for incoming TCP connections, and it wants to serversocket in a standard Java network. Examples are as follows:
Serversocketchannel Serversocketchannel = Serversocketchannel.open (); Serversocketchannel.socket (). Bind (New Inetsocketaddress (8090)); while (true) {Socketchannel Socketchannel = Serversocketchannel.accept ();}
Open a Serversocketchannel
Open by opening method
Serversocketchannel Serversocketchannel = Serversocketchannel.open ();
Close Serversocketchannel
Through the Close method
Monitor Inbound connections
Listen for foreign connections by calling the Accept method, when the Accept method returns, a connected Socketchannel is returned. So the Accept method blocks until there is a connection.
Because the general situation is not interested in listening to a single connection, you can call the Accept method within the loop.
while (true) {Socketchannel Socketchannel = Serversocketchannel.accept ();}
Of course, you should use some exit loop conditions instead of true.
Non-blocking mode
Serversocketchannel can be set to non-blocking mode, in non-blocking mode, the Accept method returns immediately, it is possible to return NULL if there is no connection established. So you have to check that the returned Socketchannel is not NULL. As follows:
while (true) {Socketchannel Socketchannel = serversocketchannel.accept (); if (Socketchannel!=null) {}}
Next section: Waiting
"Java" "NiO" 10, Java NiO serversocketchannel