Implementing HTTP protocols with NIO

Source: Internet
Author: User

First look at the directory of this blog post:

One: Introduction NiO

II: Benefits of NIO

Three: about the HTTP protocol

Four: Code implementation

V: summary

One: Introduction NiO

We all know the IO stream, so what is NIO? This blog post will take you to the full name of the Nio,nio called New Io, as the name implies, the new IO stream, launched from the Java API 1.4 release, NIO provides a completely different system of work, the IO model of Java NIO is synchronous non-blocking, That is, when the user initiates an IO operation, the edge can wait for the side to return, but requires the process to ask whether the transmission is complete, which introduces unnecessary CPU waste, but overall it is more efficient than IO, it mainly has three core components:

    • Channels
    • Buffers
    • Selectors

Channels you can understand as a channel, which is equivalent to the transmission of the pipeline, you can so abstract understanding. Buffers is a buffer, the data can be piped to the buffer, can also read through the buffer to Channel,nio the main implementation class for FileChannel, Datagramchannel, Socketchannel, Serversocketchannel,buffer's main implementation class is, from which you can see that there are many basic types of Java data, Byte, char, double, folat, int, long, and so on, Bytebuffer, Charbuffer,doublebuffer,floatbuffer,intbuffer,longbuffer,shortbuffer. While Selector is one of the most critical parts of NiO, Selector allows single-threaded processing of multiple channels, and if your application opens multiple connections (lanes), the traffic to each connection is low, and using Selector can greatly improve efficiency. To use Selector, you have to register the Channel with Selector and then call its select () method. This method will always block to a registered channel with event readiness. Once this method returns, the thread can handle these events, with examples of events like new connections coming in, data receiving, etc.

II: Benefits of NIO

In traditional socket IO, you need to create a thread for each connection, and when the number of concurrent connections is very large, the overhead of the stack memory and CPU thread context switches consumed by the thread is enormous. With NIO, you no longer need to create a separate thread for each thread, you can use a thread pool with a limited number of threads, or even a thread for any number of connection services. Because the number of threads is less than the number of connections, each thread does not block the IO operation, and if blocked, some connections are not processed, and NIO provides this non-blocking capability. When there is a task process that can implement the channel registration to selector, a slector can manage multiple threads, thus avoiding the thread's context switch, avoiding the waste of resources and greatly improving the efficiency.

Three: about the HTTP protocol

HTTP has been going through 3 generations since 1990, and the most recently used Http1.1,https are actually http1.2, Of course, this article is mainly concerned about the Http1.1,http protocol, we use a lot every day, it is based on the server and client mode, it is in the application layer to parse the content, it is a bit like our telegram, such as the need to encrypt the message before sending, send to the destination need to parse the message, corresponding to our site, in fact, every time The request is made once HTTP requests operation, this is for the client, this process will carry the address you requested, host name, user status, SessionID, cookies and other information (specifically we can use the program to implement), and then sent to the server , the server parses, and then returns to us. To learn the HTTP protocol, we have to remember the following two points:

1. No connection: The meaning of no connection is to limit the processing of only one request per connection. When the server finishes processing the customer's request and receives the customer's answer, the connection is disconnected. In this way, the transmission time can be saved.
2. Stateless: The HTTP protocol is a stateless protocol. Stateless means that the protocol has no memory capacity for transactional processing. A lack of state means that if the previous information is required for subsequent processing, it must be re-routed, which may cause the amount of data to be transferred per connection to increase. On the other hand, it responds faster when the server does not need the previous information

Four: Code implementation

Importjava.io.IOException;Importjava.net.InetSocketAddress;ImportJava.nio.channels.SelectionKey;ImportJava.nio.channels.Selector;ImportJava.nio.channels.ServerSocketChannel;ImportJava.util.Iterator; Public classServer { Public Static voidMain (string[] args)throwsIOException {serversocketchannel SSC= Serversocketchannel.open ();//listen for the new incoming TCP connection channel, open Serversocketchannelssc.socket (). Bind (NewInetsocketaddress (8080));//binding 8080 Portsssc.configureblocking (false);//set non-blocking modeSelector Selector= Selector.open ();//Creating selectorsSelectionkey Selectionkey= Ssc.register (selector, selectionkey.op_accept);//to register a channel with a selector//Selectionkey: Represents the channel registered to the Selector                 while(true) {//listening for new incoming connections                        intselect = Selector.select (2000); if(select==0) {//If you select a channel of 0, the longest will block timeout millisecondsSystem.out.println ("Wait for the request to time out ..."); Continue; } System.out.println ("Start processing requests ..."); Iterator<SelectionKey> keyiter = Selector.selectedkeys (). iterator ();//iterators                         while(Keyiter.hasnext ()) {Selectionkey key=Keyiter.next (); NewThread (NewHttpHandler (Key)). Run ();                            Keyiter.remove (); }        }    }}

Package com.wyq.NioToHttp;

Import java.io.IOException;
Import Java.nio.ByteBuffer;
Import Java.nio.channels.SelectionKey;
Import Java.nio.channels.ServerSocketChannel;
Import Java.nio.channels.SocketChannel;
Import Java.nio.charset.Charset;

/**
* HTTP Processor
* @author Yiron
*
*/
public class HttpHandler implements runnable{

private int buffersize= 1024;//set buffer size

Private String localcharset= "UTF-8"; Set the encoding format

Private Selectionkey channel for key;//registration number

Public HttpHandler (Selectionkey key) {//The selection key is constructed in

This.key = key;
}

public void Handleaccept () throws ioexception{

Socketchannel socketchannel= ((Serversocketchannel) Key.channel ()). Accept ();

Socketchannel.configureblocking (false);//Set non-blocking mode

Socketchannel.register (Key.selector (), Selectionkey.op_read,bytebuffer.allocate (buffersize));
Buffer allocates a size of 1024

}

public void Handleread () {

Socketchannel sc= (Socketchannel) Key.channel ();//Socketchannel is a channel connected to a TCP network socket

Bytebuffer buffer= (Bytebuffer) key.attachment ();//Data read from Socketchannel will be placed in this buffer

Buffer.clear ();

try {
if ((sc.read (buffer))!=-1) {

Buffer.flip ();//flip method switches buffer from write mode to read mode

String receive = Charset.forname (localcharset). Newdecoder (). Decode (buffer). toString ();
Decodes the bytes in this charset into Unicode characters

string[] Requestmessage = Receive.split ("\ r \ n");//Receive requested information

for (String message:requestmessage) {

if (Message.isempty ()) {//If the blank line description information is closed

Break
}
}
Console printing
string[] Firsetline = Requestmessage[0].split ("");

SYSTEM.OUT.PRINTLN ("----Console output:-------");

System.out.println ("Method:t" +firsetline[0]);

System.out.println ("URL is: \ t" +firsetline[1]);

System.out.println ("httpversion is: \ t" +firsetline[2]);

SYSTEM.OUT.PRINTLN ("-----Output End-------------");

Back to Client
StringBuilder sendstr = new StringBuilder ();

Sendstr.append ("http/1.1 ok\r\n");

Sendstr.append ("content-type:text/html;charset=" +localcharset+ "\ r \ n");

Sendstr.append ("\ r \ n");

Sendstr.append ("

Sendstr.append ("The message received to the request is:+<br>");

for (String s:requestmessage) {

Sendstr.append (s+ "<br/>");

}
Sendstr.append ("</body>

Buffer=bytebuffer.wrap (Sendstr.tostring (). GetBytes (Localcharset));

Sc.write (buffer);

Sc.close ();
}else {
Sc.close ();

}
} catch (IOException e) {

E.printstacktrace ();
}

}

@Override
public void Run () {

try {
if (key.isacceptable ()) {//Accept

Handleaccept ();

}
if (key.isreadable ()) {//start reading

Handleread ();

}

} catch (Exception e) {

E.printstacktrace ();
}
}


}

Print the console with the following output:

Start processing requests .....
----Console output:-------
Method:tget
The URL is:/
Httpversion is: http/1.1

Because we are bound to 8080 port, here to make a request, see the browser will print out the relevant HTTP information, as follows:

We can see a lot of information, such as our request method is: Get, host: localhost, port 8080, connection Status: Live, receive language: Chinese-English, cookile information, etc., this represents our request

Headers, this will be sent to the browser. This is the message that the HTTP protocol organizes before request requests, from which we can explore the exact HTTP, which is more profound for us to understand the client-server model. Helps us

For the development of Web sites.

V: summary

The main idea of this blog post is to learn about the use of NIO, and to understand the HTTP protocol, which contains details of the information, to understand the benefits of NIO, to understand the synchronous blocking pattern, and to implement the HTTP protocol through NIO, although there are not many opportunities for NIO to use in practice, But still helps us to deepen the understanding of the pipeline flow, the implementation of IO, I remember when I was interviewed, was asked about the difference between NiO, bio, was very blindfolded, because I do not know there are so many streams in Java. We need to learn about how single selectors handle multithreading, and how to think about threading efficiency, which is great for us.

Implementing HTTP protocols with NIO

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.