Mina, Netty, and Twisted: HTTP server, nettytwisted

Source: Internet
Author: User

Mina, Netty, and Twisted: HTTP server, nettytwisted

HTTP should be the most widely used application layer protocol. To open a website in a browser, you can use HTTP for data transmission.

The HTTP protocol is also based on the TCP protocol, so there are also servers and clients. The HTTP client is generally a browser, and of course there may be other things. HTTP Server, or Web Server, already has many mature products, such as Apache HTTP Server, Tomcat, Nginx, and IIS.

This article does not explain how to use the above HTTP server, but uses MINA, Netty, and Twisted to implement a simple HTTP server.

First, let's take a look at the HTTP protocol.

HTTP is a request/response protocol. The server returns the response content only when the client sends a request. For example, if you Enter a URL in the browser and press Enter, or submit a Form, the browser sends a request to the server, and the content of the webpage is the response returned by the server.

The following describes the content of HTTP requests and responses.

There are many methods for HTTP requests. The most common method is GET and POST. There are slight differences between requests for each method. Next we will analyze the GET and POST requests respectively.

GET request:

The following figure shows the browser's http: // localhost: 8081/test? Data sent to the server during the GET request of name = XXG & age = 23:


The request contains two parts: request line and header. The request line contains three parts: method (such as GET and POST), request uri, and protocol version. The three parts are separated by spaces. Each request line and header occupies one line and is separated by the line break CRLF (\ r \ n.

POST request:

The following is the data sent to the server when the browser sends a POST request for http: // localhost: 8081/test, with the parameter name = XXG & age = 23:


It can be seen that the above request contains three parts: request line, header, and message, which are one more message body than the previous GET request. The header and message body are separated by a blank line. The parameter of the POST request is not in the URL, but in the message body. A Content-Length Parameter in the header is used to indicate the number of bytes of the message body, so that the server can know whether the request is sent or not. This is the main difference between GET requests and POST requests.

The HTTP response is very similar to the HTTP request. The HTTP response consists of three parts: status line, header, and massage body. The status line contains three parts: protocol version, status code, and reason phrase. The status code is used to describe the HTTP response status. For example, 200 indicates that the request is successful, 404 indicates that the resource is not found, and 500 indicates that the server has an error.

HTTP response:


In the preceding HTTP response, Content-Length in the Header is also used to indicate the number of bytes of the message body. Content-Type indicates the Type of message body. Generally, the webpage Type is HTML. Of course, there are other types such as video and video.

After learning the HTTP protocol, you can use MINA, Netty, and Twisted to implement a request decoder and an HTTP server for the response encoder. In fact, there are still many details about the HTTP protocol, and it is not easy to implement it by yourself. However, MINA, Netty, and Twisted all provide HTTP-based codecs and some practical APIs.

The following uses MINA, Netty, and Twisted to implement an HTTP server and access the server via a browser:

Http: // localhost: 8080 /? Name = forks

You can open a page and display the parameters on the page:


MINA:

MINA has a mina-http-2.0.7.jar package dedicated for processing HTTP protocol. In the following code, you need to introduce the jar package to the project.

The HTTP request decoder and response encoder are HttpServerCodec. It converts an HTTP client request to an HttpRequest object and encodes the HttpResponse object into an HTTP Response and sends it to the client. Note that the implementation class objects of HttpRequest and HttpResponse do not contain the message body part. Therefore, the body in the following code is constructed through the original IoBuffer type.

Public class HttpServer {public static void main (String [] args) throws IOException {IoAcceptor acceptor = new NioSocketAcceptor (); acceptor. getFilterChain (). addLast ("codec", new HttpServerCodec (); acceptor. setHandler (new HttpServerHandle (); acceptor. bind (new InetSocketAddress (8080) ;}} class HttpServerHandle extends IoHandlerAdapter {@ Overridepublic void exceptionCaught (IoSession session, Throwable cause) throws Exception {cause. printStackTrace () ;}@ Overridepublic void messageReceived (IoSession session, Object message) throws Exception {if (message instanceof HttpRequest) {// request, the decoder converts the request to the HttpRequest object HttpRequest request = (HttpRequest) message; // gets the request parameter String name = request. getParameter ("name"); name = URLDecoder. decode (name, "UTF-8"); // response HTMLString responseHtml = "

Netty:

Netty is very similar to MINA. The only difference is that FullHttpResponse can contain the Response message body.

Public class HttpServer {public static void main (String [] args) throws InterruptedException {EventLoopGroup bossGroup = new NioEventLoopGroup (); EventLoopGroup workerGroup = new NioEventLoopGroup (); try {ServerBootstrap B = new ServerBootstrap (); B. group (bossGroup, workerGroup ). channel (NioServerSocketChannel. class ). childHandler (new ChannelInitializer <SocketChannel> () {@ Overridepublic void initChannel (SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch. pipeline (); pipeline. addLast (new HttpServerCodec (); pipeline. addLast (new HttpServerHandler () ;}}); ChannelFuture f = B. bind (8080 ). sync (); f. channel (). closeFuture (). sync ();} finally {workerGroup. shutdownGracefully (); bossGroup. shutdownGracefully () ;}} class HttpServerHandler extends {@ Overridepublic void channelRead (ChannelHandlerContext ctx, Object msg) throws UnsupportedEncodingException {if (msg instanceof HttpRequest) {/request, the decoder converts the request to HttpRequest object HttpRequest request = (HttpRequest) msg; // gets the request parameter QueryStringDecoder queryStringDecoder = new QueryStringDecoder (request. getUri (); String name = queryStringDecoder. parameters (). get ("name "). get (0); // response HTMLString responseHtml = "

Twisted:

Compared with MINA and Netty, Twisted has the most complete functions. Twisted not only includes HTTP encoder and decoder and related APIs, but also provides a complete set of Web application solutions. For more information, see the official documentation.

#-*-Coding: UTF-8-*-from twisted. web import server, resourcefrom twisted. internet import reactorclass MainResource (resource. resource): isLeaf = True # used to process GET type requests def render_GET (self, request): # name parameter name = request. args ['name'] [0] # sets the response encoding request. responseHeaders. addRawHeader ("Content-Type", "text/html; charset = UTF-8") # return directly to the response Content "


Author: Cross brother reprint please indicate the source: http://blog.csdn.net/xiao__gui/article/details/39500913







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.