1 Socketchannel
1.1 Open a Socketchannel
Socketchannel Socketchannel = Socketchannel.open ();
Socketchannel.connect (New Inetsocketaddress ("http://www.baidu.com", 80));
1.2 Closing a Socketchannel
Socketchannel.close ();
1.3 Reading a Socketchannel
Bytebuffer buf = Bytebuffer.allocate (48);
int byteread = Socketchannel.read (BUF);
2 Serversocketchannel
2.1 Serversocketchannel in blocking mode
Serversocketchannel Serversocketchannel = Serversocketchannel.open ();
Serversocketchannel.socket (). bind (New inetsocketaddress (1111));
while (true) {
Socketchannel Socketchannel = serversocketchannel.accept ();
Do something with Socketchannel ....
}
2.2 Serversocketchannel in non-blocking mode
Serversocketchannel Serversocketchannel = Serversocketchannel.open ();
Serversocketchannel.socket (). bind (New inetsocketaddress (1111));
Serversocketchannel.configureblocking (FALSE);
while (true) {
Socketchannel Socketchannel = serversocketchannel.accept ();
if (Socketchannel! = null)
{
Do something with Socketchannel ....
}
}
When no one comes to connect at non-blocking mode, the Accept () will return directly. This is also the meaning of non-blocking, for the document, always can read and write, there is no block one said, there is no non-blocking mode.
Java Socketchannel and Serversocketchannel