Java NIO Series Tutorials (eight)

Source: Internet
Author: User

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 ();
02
03 Bytebuffer buf = Bytebuffer.allocate (48);

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.