Java NiO Study Notes (2) charset and selector (asynchronous Io)

Source: Internet
Author: User
Tags socket connect

 Iii. charset)

In Java. NIO. the charset package provides five classes: charset, charsetdecoder, charsetencoder, coderesult, and codingerroraction, all of which are inherited from the object class. charset implements the comparable interface, and all other classes are self-implemented.

The characters in Java are encoded in Unicode. Each character occupies two bytes. Bytecode itself is only a number and can be correctly parsed in the correct context. When storing data to bytebuffer, you must consider the encoding method of the character set and the decoding of the character set.

Charsetdecoder and charsetencoder must be used to read and write texts respectively ).

Encoding: As defined in Encyclopedia, encoding is used to convert information into encoded values (typically numbers) for the purpose of data storage, management, and analysis on a topic or unit). In cryptography, encoding refers to the behavior written in the encoding or password. The N-bit binary number can be combined into a different information from the nth power of 2, specifying a specific code group for each information. This process is also called encoding. There are two types of commonly used encoding in Digital Systems: Binary and binary.

(1)How to obtain a charset?

Two methods are provided in the JDK source code to obtain a charset instance:

Charset cs = charset. forname ("encoding method ");

Charset cs = charset. defaultcharset ();

The first method returns a charset of the specified character format, and the second method returns the charset of the default character encoding format of the current virtual machine.

(2)How to Use charset?

After obtaining a charset instance, we need to create an encoder and a decoder, and use the following method to create it:

Charsetdecoder decoder = cs. newdecoder ();

Charsetencoder encoder = cs. newencoder ();

Next we pass bytebuffer to decoder for encoding and return a charbuffer:

Charbuffer cb = decoder. Decode (inputdata );

Then we can use encoder to decode and return a bytebuffer:

Bytebuffer outputdata = encoder. encode (CB );

Next, you can perform write and other operations.

4. selector (asynchronous Io)

Asynchronous Io is a non-blocking method for reading and writing data. Generally, when the code is called for read (), the code blocks until there is data available for reading. Similarly, the write () call will block until data can be written.

One advantage of asynchronous I/O is that it allows you to execute I/O simultaneously based on a large amount of input and output. Synchronization programs often have to turn to polling, or create many threads to process a large number of connections. With asynchronous I/O, you can listen to events on any number of channels without polling or additional threads.

The core object in asynchronous I/O is called selector. Selector is the place where you register various I/O events, and when those events occur, it is the event that this object tells you.

Step 1: Create a selector

Selector selector = selector. open ();

Step 2: open a remote connection

Inetsocketaddress socketaddress =

New inetsocketaddress ("www.baidu.com", 80 );

Socketchannel SC = socketchannel. Open (socketaddress );

SC. configureblocking (false );

Step 3: select the key and register

Selectionkey key = SC. Register (selector, selectionkey. op_connect );

The first parameter is always the current selector during registration.

Register read events: selectionkey key = SC. Register (selector, selectionkey. op_read );

Register the write event: selectionkey key = SC. Register (selector, selectionkey. op_write );

Step 4: Internal cyclic Processing

Int num = selector. Select ();

Set selectedkeys = selector. selectedkeys ();

Iterator it = selectedkeys. iterator ();

While (it. hasnext ()){

Selectionkey key = (selectionkey) it. Next ();

//... Deal with I/O event...

}

First, we call the select () method of selector. This method will be blocked until at least one registered event occurs. When one or more events occur, the Select () method returns the number of events that occur. This method must be executed first.

Next, we call selectedkeys () method of selector, which returns a set of selectionkey objects in which the event occurs.

We iterate selectionkeys and process each selectionkey in sequence to process events. For each selectionkey, you must determine what an I/O event occurs and what I/O objects this event affects.

Step 5: listen to and handle events

Selectionkey defines four types of events: op_accept (socket accept), op_connect (socket Connect), op_read (read), and op_write (write ).

Step 6: Delete the processed selectionkey

After processing the selectionkey, We can almost return the main loop. However, we must first Delete the processed selectionkey from the selected key set.

If we have not deleted the processed key, it will still appear in the master set with an active key, which will cause us to try to process it again.

We call the remove () method of the iterator to delete the processed selectionkey: it. Remove ();

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.