Mina, Netty, Twisted learn together (eight): HTTP server

Source: Internet
Author: User

HTTP protocol should be the most used application layer protocol, open a Web site with a browser is to use the HTTP protocol for data transmission.

The HTTP protocol is also based on the TCP protocol, so there are servers and clients. The HTTP client is generally a browser and, of course, it could be something else. HTTP server, which is the Web server, now has a lot of mature products, such as Apache HTTP Server, Tomcat, Nginx, IIS and so on.

The content of this article is not to explain how to use the above HTTP server, but to use Mina, Netty, twisted to implement a simple HTTP server.

First, take a quick look at the HTTP protocol.

The HTTP protocol is a request/response protocol, and the client needs to send a request before the server returns the response content. For example, enter a URL on the browser to press ENTER, or submit a form form, the browser will send a request to the server, and the content of the open Web page is the response returned by the server.

Here's a look at what the HTTP request and response contains.

There are many methods of HTTP requests, the most common being get and post, and there is a slight difference between requests for each method. The Get and post requests are analyzed separately below.

GET Request:

The following is the data that the browser sends to the server when the http://localhost:8081/test?name=XXG&age=23 GET request:


You can see that the request contains both the requests line and the header. Where request line contains method (such as Get, POST), request URI, and protocol version three parts, three parts separated by a space. The request line and each header occupy a line, separated by a newline character crlf (\ r \ n).

POST request:

The following is the data sent to the server by the browser's post request to Http://localhost:8081/test, with the same parameter name=xxg&age=23:


As you can see, the above request contains three parts: Requests line, header, message, more than the previous GET request a message body, where the header and message body separated by a blank line. The parameters of the POST request are not in the URL, but in the message body, where a content-length is used to represent the number of bytes in the message body, so that the server knows whether the request was sent or not. This is the main difference between a GET request and a POST request.

HTTP responses are very similar to HTTP requests, and the HTTP response consists of three parts: status line, header, massage body. Where status line contains protocol version, status code, reason phrase three parts. Status codes are used to describe the status of HTTP responses, such as 200 for success, 404 for resources not found, and 500 for server errors.

HTTP response:


In the HTTP response above, the Content-length in the header is also used to represent the number of bytes in the message body. Content-type represents the type of message body, usually browse the Web page its type is HTML, of course there will be other types, than slices, videos and so on.

After learning the HTTP protocol, it is possible to implement an HTTP server for the requested decoder and the encoder for the response, respectively, through Mina, Netty, and twisted. In fact, there are many details of the HTTP protocol, and it is not easy to implement them. However, MINA, Netty, and twisted have already provided codecs and some useful APIs for the HTTP protocol.

The following respectively with Mina, Netty, twisted to implement an HTTP server, with a browser access:

Http://localhost:8080/?name= Fork Brother

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


MINA:

There is a Mina-http-2.0.7.jar package in Mina that is designed to handle the HTTP protocol. In the following code, this jar package needs to be introduced into the project.

The request decoder and Response encoder for the HTTP protocol is HTTPSERVERCODEC, which converts an HTTP client request to an HttpRequest object, encodes the HttpResponse object into an HTTP response, and sends it to the client. It is important to note that the HttpRequest and HttpResponse implementation class objects do not contain the message body part, so the body in the code below is also constructed from the original Iobuffer type.

public class Httpserver {public static void main (string[] args) throws IOException {Ioacceptor acceptor = new NIOSOCKETACC Eptor (); 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, decoder converts request to HttpRequest object HttpRequest ask = (HttpRequest) message;//GET request parameter String name = Request.getparameter ("name"); name = Urldecoder.decode (name, "UTF-8");//Response htmlstring responsehtml = "
Netty:

Netty and Mina are very similar. The only difference is that the fullhttpresponse can contain the message body of the response.

public class Httpserver {public static void main (string[] args) throws Interruptedexception {Eventloopgroup Bossgroup = NE W 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 ());p Ipeline.addlast (New Httpserverhandler ());}); Channelfuture f = b.bind (8080). sync (); F.channel (). Closefuture (). sync (); finally {workergroup.shutdowngracefully (); bossgroup.shutdowngracefully ();}}} Class Httpserverhandler extends Channelinboundhandleradapter {@Overridepublic void Channelread (Channelhandlercontext CTX, Object msg) throws Unsupportedencodingexception {if (msg instanceof HttpRequest) {//request, The decoder translates the request into a HttpRequest object HttpRequest ask = (HttpRequest) msg;//GET request parametersQuerystringdecoder Querystringdecoder = new Querystringdecoder (Request.geturi ()); String name = Querystringdecoder.parameters (). Get ("name"). Get (0);//Response htmlstring responsehtml = "
Twisted:

Twisted HTTP is the most complete feature compared to Mina and Netty. The twisted includes both encoders and decoders for the HTTP protocol and related APIs, as well as a complete set of Web application solutions. For a complete study, you can refer to the official documentation.

#-*-Coding:utf-8–*-from twisted.web import server, resourcefrom twisted.internet import reactorclass mainresource (Reso Urce. Resource):        isleaf = True        # used to process GET type request    def render_get (self, request):                # Name parameter        name = Request.args [' Name '] [0]                # Set Response encoding        request.responseHeaders.addRawHeader ("Content-type", "text/html; Charset=utf-8 ")                        # Response content returned directly        to" 


Fork Brother reproduced please indicate the source: http://blog.csdn.net/xiao__gui/article/details/39500913




Mina, Netty, Twisted learn together (eight): HTTP server

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.