"Java" "NiO" 10, Java NiO serversocketchannel

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.