Netty Advanced Article-websocket Protocol development

Source: Internet
Author: User
Tags base64 encode

Reading directory One, the drawbacks of the HTTP protocol Ii. WebSocket Protocol Introduction III, WebSocket Connection IV, Protocol Development v. Client and test back to top one, disadvantages of HTTP protocol

The main drawbacks of HTTP protocol are summarized as follows: (1) Half-duplex protocol: It can be transmitted in 2 directions of client and server, but not simultaneously. At the same time, it can only be transmitted in one direction. (2) HTTP message verbose: A bit cumbersome compared to other binary protocols. (3) Hacker attacks against server push, such as long polling.

Many Web sites now use polling for messages, that is, the client sends a request to the server every 1S or other time, and the server returns the latest data to the client. The header in the HTTP protocol is very verbose and therefore consumes a lot of bandwidth and server resources.

The newer technology is comet, which uses Ajax. Although two-way communication is possible, requests are still sent, and long connections are commonly used in comet, which consumes a lot of server bandwidth and resources.

To solve this problem, HTML5 defines the WebSocket protocol. Back to top ii. introduction of WebSocket protocol

In the WebSocket API, the browser and the server only need a handshake action, then the browser and the server formed a fast channel between the two can directly transmit data to each other.

WebSocket based on TCP bidirectional Full-duplex protocol, that is, at the same time, that is, can send messages, also can receive messages, compared to the HTTP protocol, is a performance improvement.

Features: Single TCP connection, Full-duplex, transparent to agents, firewalls and routers, no header information, cookies and authentication, no security overhead, and link activation through "ping/pong" frames; The server can deliver the message to the client voluntarily and no longer needs the client polling;

WebSocket with the above features is to replace polling and comet technology, so that the client browser with the C/s architecture under the same real-time capabilities of the desktop system.

Browser through JS to establish a websocket request, the connection is established, the client and server side can directly exchange data through TCP.

Because WebSocket is inherently a TCP connection, it is stable, so it has a performance advantage over Comet and polling, as shown in the figure:

Back to top three, websocket connection 3.1 connection established

The client side sends a handshake request with the request message as shown in the figure:

Unlike ordinary HTTP requests, this request contains additional header information, where the additional header information "Upgrade:websocket" indicates that this is an HTTP request for a protocol upgrade. The server attempts to parse this information and then returns the answer to the client, so the WebSocket connection between the client and the server is established, and the two parties can pass the information freely through the connection channel. This connection lasts until one of the parties is actively disconnected.

The service-side response request is shown in the figure:

The "Sec-websocket-key" in the client message is random, and the server side uses the data to construct a "SHA-1" summary of the information, adding "Sec-websocket-key" to a magical string. Use "SHA-1" to encrypt and then BASE64 encode the result as the value of the "Sec-webscoket-accept" header. 3.2 life cycle handshake success, the connection is established, in a "Messages" way of communication. A message consists of one or more "frames". Frames have their own types, and the same message has multiple frame types. Broadly speaking, types can be text, binary, control frames such as signals.

The 3.3 Connection shutdown Security method is to turn off the underlying TCP connection and the TLS session. The underlying TCP connection, under normal circumstances, should be shut down by the server first. When an exception, such as TCP Close for a server is not received within a reasonable time, TCP close can be initiated by the client. Therefore, when the client initiates TCP close, the server should immediately initiate a TCP close operation; The client waits for the server's TCP closing; The shutdown message comes with a status code and optional shutdown reason, and it must send a close control frame as required by the Protocol. Back to top Iv. protocol development

Official demo:http://netty.io/4.1/xref/io/netty/example/http/websocketx/server/package-summary.html

Feature Introduction: Server-side development:

Import Io.netty.bootstrap.ServerBootstrap;
Import Io.netty.channel.Channel;
Import Io.netty.channel.ChannelInitializer;
Import Io.netty.channel.ChannelPipeline;
Import Io.netty.channel.EventLoopGroup;
Import Io.netty.channel.nio.NioEventLoopGroup;
Import Io.netty.channel.socket.SocketChannel;
Import Io.netty.channel.socket.nio.NioServerSocketChannel;
Import Io.netty.handler.codec.http.HttpObjectAggregator;
Import Io.netty.handler.codec.http.HttpServerCodec;

Import Io.netty.handler.stream.ChunkedWriteHandler; /** * @author Lilinfeng * @version 1.0 * @date February 14, 2014/public class Websocketserver {public void run (int po
        RT) Throws Exception {Eventloopgroup bossgroup = new Nioeventloopgroup ();
        Eventloopgroup Workergroup = new Nioeventloopgroup ();
            try {serverbootstrap b = new Serverbootstrap (); B.group (Bossgroup, Workergroup). Channel (Nioserversocketchannel.class). Childhandl ER (new ChanneliNitializer<socketchannel> () {@Override protected void Initchannel ( Socketchannel ch) throws Exception {Channelpipeline pipeline
                            = Ch.pipeline ();
                            Pipeline.addlast ("Http-codec", New Httpservercodec ());
                            Pipeline.addlast ("Aggregator", New Httpobjectaggregator (65536));
                            Ch.pipeline (). AddLast ("http-chunked", New Chunkedwritehandler ());
                        Pipeline.addlast ("Handler", New Websocketserverhandler ());

            }
                    });
            Channel ch = b.bind (port). Sync (). Channel ();
            SYSTEM.OUT.PRINTLN ("Web socket server started at port" + Port + '. ');
     System.out               . println ("Open your browser and navigate to http://localhost:" + port + '/');
        Ch.closefuture (). sync ();
            finally {bossgroup.shutdowngracefully ();
        Workergroup.shutdowngracefully ();
        } public static void Main (string[] args) throws Exception {int port = 8080;
            if (Args.length > 0) {try {port = integer.parseint (Args[0]);
            catch (NumberFormatException e) {e.printstacktrace ();
    } new Websocketserver (). Run (port); }
}

HTTPSERVERCODEC: Decoding request and reply messages to HTTP messages

Httpobjectaggregator: Synthesizing multiple parts of an HTTP message into a complete HTTP message

Chunkedwritehandler: Send HTML5 file to client

Looks very similar to the HTTP protocol, look for answers from handler:

 1 import io.netty.buffer.ByteBuf;
  2 Import io.netty.buffer.Unpooled;
  3 Import io.netty.channel.ChannelFuture;
  4 Import Io.netty.channel.ChannelFutureListener;
  5 Import Io.netty.channel.ChannelHandlerContext;
  6 Import Io.netty.channel.SimpleChannelInboundHandler;
  7 Import Io.netty.handler.codec.http.DefaultFullHttpResponse;
  8 Import Io.netty.handler.codec.http.FullHttpRequest;
 9 Import Io.netty.handler.codec.http.FullHttpResponse;
 Import Io.netty.handler.codec.http.HttpUtil;
 Import io.netty.handler.codec.http.websocketx.*;
 Import Io.netty.util.CharsetUtil;
 Import Java.util.logging.Level;
 Import Java.util.logging.Logger;
 Import static Io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
 Import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; /** * @author Lilinfeng * @version 1.0 * @date February 14, 2014 

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.