The Socketchannel of Java NiO is the channel that connects TCP network sockets. There are two ways to create:
1. Open a socketchannel and connect to a server on the network
2. When Serversocketchannel receives a connection, Socketchannel creates a
Open Socketchannel
Socketchannel Socketchannel = Socketchannel.open () socketchannel.connect (New Inetsocketaddress ("127.0.0.1", 8090));
Close Socketchannel
Socketchannel.close ();
Read data from Socketchannel
Read the data by reading method, as follows:
Bytebuffer buffer = bytebuffer.allocate (ten); int bytesread = socketchannel.read (buffer);
The cache is allocated first, and the data read from Socketchannel is read into buffer.
Second, the Read method returns an int indicating how many bytes were read into buffer, returning 1, indicating that the end of the stream was read, and the connection was closed.
Write data to Socketchannel
Write the data into the Socketchannel by using the Write method, as follows:
Bytebuffer buffer = bytebuffer.allocate (ten); Buffer.clear () buffer.put ("Simon". GetBytes ()); Buffer.flip (); while ( Buffer.hasremaining ()) {//write file Channel.write (buffer);}
Notice that the Write method is called repeatedly to instruct that no data is writable in buffer.
Non-blocking mode
You can set Socketchannel to non-blocking mode. In this case, you can call the Connect,read,write method asynchronously.
Connect ()
If Socketchannel is non-blocking mode, and you call the Connect method, the method will return before the connection is established. To determine if the connection is established, you can call the Finishconnect () method, as follows:
Socketchannel.configureblocking (false); Socketchannel.connect (New Inetsocketaddress ("127.0.0.1", 8090), while (! Socketchannel.finishconnect ()) {System.out.println ("Connection not established ...");
Write ()
In nonblocking mode, the Write method may return without writing any data. So you need to loop through the Write method. Examples are in front of them.
Read ()
In the same non-blocking mode, the Read method may return without reading any data, so you need to be aware of the integer value returned by the Read method, indicating how many bytes have been read.
Non-blocking modes and selectors
The non-blocking mode works better with selector. By registering one or more socketchannel on a selector, you can ask selector which channels are ready to read and write. How to use the follow-up will be explained in detail.
Next section: "Java" "NiO" 10, Java NIO Serversocketchannel
"Java" "NiO" 9, Java NiO socketchannel