Netty in Action (23) 12th Chapter WebSocket

Source: Internet
Author: User
Tags rfc

Part III: Network protocols


WebSocket is an advanced network protocol developed to improve the performance of the network and the response rate of Web applications, we will introduce Netty support for these two features websocket, and we will give a simple example to explain the features of the two WebSocket


In the 12th chapter, you will learn how to use WebSocket to realize the function of bidirectional transmission of data, we will write a chat room to explain this data bidirectional transmission problem, our chat room example is this: multiple browser clients are real-time communication with each other, You will also learn how to upgrade the normal HTTP protocol to the WebSocket protocol, but we need to detect in advance whether the client supports WebSocket


We will also end up with the third part of the Netty to the user Dategram Protocol (UDP) protocol support, we will build a broadcast mechanism of the server, and will monitor the state of the client, so that the client can apply more practical use



The 12th chapter: WebSocket

The contents of this chapter include:

1) concept of real-time network

2) WebSocket Protocol

3) using Netty to build a websocket-based chat room server


If you are familiar with the recent development of Web applications, you will certainly be exposed to the "real-time web" concept, if you have real-time systems have experience in combat, you may be questioning the "real-time web" What this means


So we need to clarify this concept in the beginning, this is not what we call "full real-time quality service", we can call it "near real-time service", in this scenario, the calculation results of the background must be transmitted within the specified time, the specified time compared to the guarantee, But the HTTP protocol design of the request response is not suitable for this scenario, and if there are a lot of problems with this scenario, because you don't know when to request it, as of now, it turns out that no plan has been designed yet, and no plan has been considered satisfactory.


Although there is still much academic discussion about the definition of the term "timed Web services", the universally accepted concept has not yet emerged so far, we can only accept from Wikipedia a not authoritative definition of the real-time Web:

A near-real-time web is a network Web system that requires the use of a technology or a strategy that enables users to obtain information as quickly as possible, rather than requiring users or clients to use their software to proactively invoke or detect whether a data source has changed


Technically, perhaps a mature real-time web may not have really come, but in this philosophy will accelerate the expectations of this technology, with this technology you can almost instantaneous to obtain information, The WebSocket protocol discussed in this chapter is a very solid step forward in the research direction of near real-time technology.


12.1 Introducing WebSocket


The WebSocket protocol is a practical solution designed to address the bidirectional transmission of data in Web applications, which can be used by servers and clients to transmit information in any event, so that they can be processed asynchronously by the information


Netty's support for WebSocket includes many of the main implementations of WebSocket, so it's straightforward to directly use the WebSocket service provided by Netty directly in your project, as is the concept of netty design. You can fully use the WebSocket protocol without needing to care about its internal implementation details, we will create a real-time web version of the chat system by using the WebSocket protocol


12.2 Our example WebSocket application


Our example application will use the WebSocket protocol to implement a browser-based chat app to illustrate the functionality of real-time communication, which is similar to the kind of text message you encounter on Facebook, and we will support our example to enable multiple users to communicate with each other at the same time.


Figure 12.1 illustrates the main logic of our example

1) client sends information

2) The information sent is broadcast to all other linked clients


This is the basic logic of how a chat room works: Everyone can talk to everyone else, in our example we will only implement our service-side code, the client is through some of the browser's functions to achieve simple, in the next few pages of content, You'll see how Netty's websocket is simply building this example.


12.3 Adding WebSocket Support


The upgrade handshake mechanism is used to switch the standard HTTP protocol or HTTPS protocol to the WebSocket protocol, and of course an application will be upgraded to a WebSocket application with http/s starting in a scenario that requires an upgrade, which can be triggered by a specific URL designation


Our application will use such an upgrade mechanism, if a URL request is the end of/WS, we will upgrade the protocol to the WebSocket protocol, otherwise we use the most basic HTTP/S protocol by default, when the connection is successfully upgraded, all data will be propagated using the WebSocket protocol , Figure 12.2 illustrates the server logic, the server is using Netty, specifically through a series of channelhandler implementation, in the next section, we will specifically describe these components, we will explain these processing HTTP and WebSocket protocol technology


12.3.1 Handling HTTP Requests


First we will implement the component to handle the HTTP request, which serves on the Web page to provide a portal to the chat room and to show the display of information sent by each connected client Listing 12.1 shows the implementation of Httprequesthandler, which inherits from the Simplechannelinboundhandler used to process fullhttprequest information, notice how the implementation of the method channelRead0 is handled in the code implementation The URI of the request that ends in/ws.

If there is "/ws" in a URI request, Httprequesthandler will raise the retain method on Fullhttprequest and then pass Firechannelread (msg) method to move it to the next channelinboundhandler, it is necessary to call retain because it will call the release method on Fullhttprequest to release the resource after the Channelread method completes.


If a client sends a HTTP1.1 message header expecting a "100-continue", then Httprequesthandler will send a 100-continue response after all headers have been set, Httprequesthandler will write a httpresponse to return to the client, returning is not a complete fullhttpresponse, because it is only the first part of the response, so here does not call the Writeandflush method, This method will be called at the end of the



If both encryption and compression are not required, Then we can store the contents of index.html in defaultfileregion, so that we can get the maximum efficiency, so that we can use 0 copy technology to get the highest transfer efficiency, for this reason, you can understand whether there is sslhandler in a channelpipeline, such as If you have one, you have the option to use Chunkedniofile


Httprequesthandler write a lasthttpcontent to mark the end of a response, if keepalive is not required, Then Httprequesthandler will add a channelfuturelistener to close the connection at the end of the last write Channelfuture Here you can call the Writeandflush method to flash all the information written into


So far, this code represents the first module of the chat room, it will manage the pure HTTP request and response, the next section, we will process the WebSocket protocol frame data, this data will carry the real chat information


12.3.2 Handling WebSocket Frames


The RfC's WebSocket protocol, published by the IETF, regulates six types of frame data, Netty provides a POJO implementation for each frame data, and table 12.1 lists the types of these frame data and describes their usage instructions.



Our chat room will use the following data frame type

1) closewebsocketframe

2) Pingwebsocketframe

3) Pongwebsocketframe

4) Textwebsocketframe


In fact, the textwebsocketframe type of data is what we really need to deal with, for RFC-compliant Websocket,netty provides websocketserverprotocolhandler to manage other types of frame data



The following code listing shows the Channelinboundhandlerused to handle textwebsocketframe, which can also be used to track the surviving WebSocket connection in Channelgroup.


Textwebsocketframehandler is only responsible for a small piece of functionality, and when WebSocket successfully shook hands with the new client, it will notify all the connected clients. By writing it to all the channel Channelgroup, then it writes the new channel to the Channelgroup


If a textwebsocketframe is received, it calls the Retain method on the Textwebsocketframe object, The Writeandflush method is then used to transmit it to the channelgroup so that all connected WebSocket channel can receive this message.


Before, it is necessary to call the Retain method, because when the ChannelRead0 method returns textwebsocketframe the count reference of the object decrements by one, because all operations are asynchronous, Writeandflush may be completed within a certain delay, so we are not allowed to get an illegal object reference, so call the Retain method


Because Netty internally has done most of the work for our WebSocket implementation, the only thing left is to initialize the good channelpipeline, because every new channel is created here, for this reason, We need a channelinitializer.


12.3.3 Initializing the Channelpipeline


As we have learned before, when installing Channelhandler in Channelpipeline, you only need to inherit the Channelinitializer class, and then implement the Initchannel method, The following code listing shows the actual code for the Chatserverinitializer

The call to the Initchannel method can be set to the channel registered in the Channelpipeline, which allows you to install all of the required channelhandler, gives a partial summary in table 12.2, each describing their own function





Netty Websocketserverprotocolhandler handles all authorized WebSocket frame types of data, and simultaneously upgrades the handshake, if the handshake succeeds, some of the specified channelhandler need to be added to the pipeline, If not needed, these handler will no longer be removed from the pipeline




As shown in state 12.3 of the pipeline before the protocol upgrade, this diagram represents the state of the pipeline after the Chatserverinitializer initialization.


When the protocol is upgraded, Websocketserverprotocolhandler will replace Httprequestdecoder with Websocketframedecoder, Replace Httpresponseencoder with Websocketframeencoder
, in order to maximize performance, it will remove any unwanted handler at this time, these handler may websocket not be used, These handler include the Httpobjectaggregator and Httprequesthandler as shown in 12.3




< Span style= "font-family:courier; Color: #000000; font-size:10pt; Font-style:normal; Font-variant:normal ">
12.3.4 Bootstrapping

The last module of this chat room is to start the server initialize all the Chatserverinitializer, these actions will be chatserver processed, as shown below

All the code for the app has been completed, and now we're going to test

12.4 Testing the Application


All of the code examples in the 12th section have been given, and now you need to build a run test case, and we can use the following MAVEN command to build and start the project



The pom.xml of this project is configured in the Port 9999来 startup project, if you want to use other ports, you can not need to edit the amount of change, you can re-overwrite the variable in the command

The following is a diary of the build and startup of the console print



Enter http://localhost:9999 in your browser to enter your app, Figure 12.5 shows the Chrome browser UI


Figure 12.5 shows the two linked clients, the first connection is using the input interface provided by the browser page header, the second connection is connected through the console at the bottom of the browser, you will find that regardless of the information sent from both clients, the information sent can be displayed in other clients normally


This is a complete example, which is a good example of how websocket constructs a real-time communication in a browser.


12.4.1 What's about encryption?


In a real production environment, you will soon be asked to add the encryption to your application, for Netty applications, this is a trivial matter, you just need to add Sslhandler to Channelpipeline and then configure it, The following code listing shows how we can do this, and we just need to create a securechatserverinitializer to inherit it with Chatserverinitializer.



The final step is to let Chatserver take the Securechatserverinitializer we just created so that we can get Sslhandler into the pipeline, we use securechatserver this effect is achieved.

This allows the entire communication to support SSL/TLS encryption, as before, we still use MAVEN to build

And now you can see Securechatserver in http://localhost:9999.


12.5 Summary

In this chapter, we use the Netty implementation of WebSocket to write a web-version of the real-time data system, we explained the websocket supported data types, but also discussed some of the limitations we encountered, although not every scene can be used WebSocket, But there is no doubt that, for web development, WebSocket technology is an important breakthrough in this area.




Netty in Action (23) 12th Chapter WebSocket

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.