The method of implementing WebSocket by Tomcat _tomcat

Source: Internet
Author: User
Tags tomcat

The WebSocket protocol belongs to the HTML5 standard, and more and more browsers already natively support WebSocket, which enables two-way communication between client and server. After establishing a WebSocket connection on the client and server side, server-side messages can be sent directly to the client, thus breaking the traditional request-response mode and avoiding meaningless requests. For example, traditional methods may use AJAX to continuously request the server side, while WebSocket can send data directly to the client and the client does not need to request. At the same time, with the native support of browsers, writing client applications becomes more convenient and eliminates the need to rely on Third-party plug-ins. In addition, the WebSocket protocol rejects the cumbersome request header of HTTP protocol, but transmits it in data frame, which is more efficient.

Figure for the WebSocket protocol communication process, first the client will send a handshake packet told the server side I want to upgrade to WebSocket, do not know if you agree with the server, then if the server-side support WebSocket protocol will return a handshake packet to tell the client, upgrade has been confirmed. A websocket connection is then successfully established, which supports bidirectional communication and sends messages using the WebSocket protocol's data frame format.

The handshake needs to be explained, in order for the WebSocket protocol to be compatible with the existing HTTP protocol Web architecture, 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 upgrade:websocket that tells the server that 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-version: 13

At this point, if the server side supports the WebSocket protocol, it sends a message that agrees to the client escalation protocol, which is similar to the following, where Upgrade:websocket is telling the client that I agree to your upgrade agreement:

http/1.1 WebSocket Protocol Handshake
Date:fri, a Feb 2016 17:38:18 GMT connection:upgrade
Server:kaaz ing Gateway
upgrade:websocket
sec-websocket-accept:rlhckw/skso9gah/zsfhbatdkru=

Complete as the handshake, the HTTP protocol connection is broken, and then 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 how to write WebSocket in Tomcat:

 public class Hellowebsocketservlet extends Websocketservlet {private static List<mes
sageinbound> socketlist = new arraylist<messageinbound> (); Protected Streaminbound Createwebsocketinbound (String subprotocol,httpservletrequest request) {return new
Websocketmessageinbound (); public class Websocketmessageinbound extends messageinbound{protected void onClose (int status) {Super.onclose (status)
; 
Socketlist.remove (this); } protected void OnOpen (Wsoutbound outbound) {super.onopen (outbound); Socketlist.add (this); @Override protected void on Binarymessage (Bytebuffer message) throws IOException {} @Override protected void Ontextmessage (Charbuffer message) throw
S IOException {for (Messageinbound messageinbound:socketlist) {Charbuffer buffer = charbuffer.wrap (message);
Wsoutbound outbound = Messageinbound.getwsoutbound ();
Outbound.writetextmessage (buffer); 
Outbound.flush (); }
}
}
}

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

According to the above processing logic, the WebSocket integration of Tomcat 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 right time. Because WebSocket is generally recommended for use in NIO mode, look at the NIO mode integration WebSocket protocol.

For example, if a WebSocket client connection is received by the receiver and is registered into the Niochannel queue, the Poller component will have niochannel to be processed. If there is a processing pipeline that is backward to the Websocketservlet servlet, the Websocketservlet Doget method handles the WebSocket handshake and tells the return client to agree to the upgrade protocol. Poller continue to keep the rest of the Niochannel, once found that the pipeline using the WebSocket protocol will call Messageinbound related methods to complete the processing of different events, so as to achieve the WebSocket protocol support.

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.