How Tomcat implements WebSocket

Source: Internet
Author: User

The WebSocket protocol belongs to the HTML5 standard, and more and more browsers have natively supported WebSocket, which enables two-way communication between client and server. After a websocket connection is established on the client and server side, the server-side message can be sent directly to the client, thus breaking the traditional request-response pattern and avoiding meaningless requests. For example, the traditional approach may use Ajax to constantly request the server side, while WebSocket can send data directly to the client and the client does not have to request. At the same time, because of the native support of the browser, writing a client application becomes more convenient and does not have to rely on third-party plugins. In addition, the WebSocket protocol rejects the cumbersome request header of the HTTP protocol, but transmits it in a data frame, which is more efficient.

Figure for the WebSocket protocol communication process, first the client will send a handshake packet to tell the server side I want to upgrade to WebSocket, do not know whether your server-side consent, at this time if the server-side support WebSocket protocol will return a handshake packet to tell the client no problem, the upgrade has been confirmed. A websocket connection is then successfully established, which supports bidirectional communication and sends messages using the data frame format of the WebSocket protocol.

The handshake process needs to be explained, in order for the WebSocket protocol to be compatible with the existing HTTP protocol Web schema, the handshake of the WebSocket protocol is based on the HTTP protocol, for example, the client sends an HTTP message similar to the following to the server-side request upgrade to the WebSocket protocol , which contains the upgrade:websocket is to tell the server side I want to upgrade the protocol:

    GET ws://localhost:8080/hello HTTP/1.1    Origin: http://localhost:8080    Connection: Upgrade    Host: localhost:8080    Sec-WebSocket-Key: uRovscZjNol/umbTt5uKmw==    Upgrade: websocket    Sec-WebSocket-Version13

At this point, if the server-side support WebSocket protocol, it will send a consent to the Client Upgrade protocol message, the specific message is similar to the following, where Upgrade:websocket is to tell the client I agree to your upgrade agreement:

    HTTP/1.1101 WebSocket Protocol Handshake    Date10201617:38:18 GMT    Connection: Upgrade    Server: Kaazing Gateway    Upgrade: WebSocket    Sec-WebSocket-Accept: rLHCkw/SKsO9GAH/ZSFhBATDKrU=

After the completion of the handshake, the HTTP protocol connection is broken, the next is to start using the WebSocket protocol for both sides of the communication, this connection is the original TCP/IP connection, the port is still the original 80 or 443.

Here's a simple example of scripting WebSocket in Tomcat:

 Public  class hellowebsocketservlet extends websocketservlet {    Private StaticList<messageinbound> socketlist =NewArraylist<messageinbound> ();protectedStreaminboundCreatewebsocketinbound(String subprotocol,httpservletrequest request) {return NewWebsocketmessageinbound (); } Public  class websocketmessageinbound extends messageinbound{        protected void OnClose(intStatus) {Super. OnClose (status); Socketlist.remove ( This); }protected void OnOpen(Wsoutbound Outbound) {Super. OnOpen (outbound); Socketlist.add ( This); }@Override        protected void Onbinarymessage(Bytebuffer message)throwsIOException {}@Override        protected void Ontextmessage(Charbuffer message)throwsIOException { for(Messageinbound messageinbound:socketlist)                {Charbuffer buffer = charbuffer.wrap (message);                Wsoutbound outbound = Messageinbound.getwsoutbound ();                Outbound.writetextmessage (buffer);                           Outbound.flush (); }        }    }}

The servlet must inherit Websocketservlet and then create a Websocketmessageinbound class that inherits Messageinbound, populating the class with OnClose, OnOpen, Methods such as Onbinarymessage and Ontextmessage can complete the logic of each event, where OnOpen is called when a websocket connection is established, and OnClose is called when a websocket is closed. Onbinarymessage is called when the client data is received in binary mode, and Ontextmessage is called when the client data is received in text mode. The previous section of code implements a broadcast effect.

According to the above processing logic, the integration of Tomcat to WebSocket is not too difficult, that is, when processing the request, if encountered WebSocket protocol request to do special processing, Keep the connection and call Websocketservlet's Messageinbound onclose, OnOpen, Onbinarymessage, and ontextmessage at the appropriate time. Since WebSocket is generally recommended for use in NIO mode, look at the NIO mode integration WebSocket protocol.

, for the WebSocket client connection is registered to the Niochannel queue after the receiver is received, the Poller component constantly rested whether there is niochannel to handle, If there is a processing pipeline that is backward to the servlet that inherits Websocketservlet, the Websocketservlet Doget method handles the WebSocket handshake and tells the return client to agree to the upgrade protocol. Poller continue to rested related niochannel, once found that the use of WebSocket protocol pipeline will call Messageinbound related methods, complete the processing of different events, so as to achieve the WebSocket protocol support.

How Tomcat implements 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.