Reprinted from Concurrent Programming Network –ifeve.com This article link address: Java NIO series Tutorial (eight) Socketchannel
The Socketchannel in Java NiO is a channel that is connected to a TCP network socket. You can create Socketchannel in 2 ways: Open a socketchannel and connect to a server on the Internet. When a new connection arrives at Serversocketchannel, a socketchannel is created.
Open Socketchannel
The following is how Socketchannel is opened:
| 1 |
Socketchannel Socketchannel = Socketchannel.open (); |
| 2 |
Socketchannel.connect (New Inetsocketaddress ("http://jenkov.com", 80)); |
Close Socketchannel
Call Socketchannel.close () Close Socketchannel after Socketchannel is exhausted:
| 1 |
Socketchannel.close (); |
reading data from Socketchannel
To read data from Socketchannel, call one of the Read () methods. Here is an example:
| 1 |
Bytebuffer buf = Bytebuffer.allocate (48); |
| 2 |
int bytesread = Socketchannel.read (BUF); |
First, allocate a buffer. The data read from the Socketchannel will be placed in this buffer.
Then, call Socketchannel.read (). This method reads the data from the Socketchannel into the buffer. The int value returned by the Read () method indicates how many bytes were read into the buffer. If-1 is returned, it means that the end of the stream has been read (the connection is closed). Write to Socketchannel
The Socketchannel.write () method is used to write data to Socketchannel, which takes a buffer as an argument. Examples are as follows:
| 01 |
String NewData = "New String to write to file ..." + System.currenttimemillis (); |
| 03 |
Bytebuffer buf = Bytebuffer.allocate (48); |