Tomcat 7 WebSocket implementation (below)
Author: chszs, reprinted with note. Blog homepage: http://blog.csdn.net/chszs
Let's take a look at the interaction of WebSocket:
1) "Connection: upgrade" in the header"
2) The response contains a critical status code of 101.
3) indicates that the protocol exchange has been proved
After the handshake between the client and the server is complete, the request/response communication is discarded and messages are sent to each other independently. Below is my frame:
How does Tomcat implement WebSocket?
1) to start using WebSocket, you must inherit the WebSocket class of Tomcat.
2) write your own class, which inherits the WebSocketServlet class (because this is a Servlet, you must map it to the URL)
3) implement a message listener class. Because it inherits from the WebSocketServlet class, you must implement the createWebSocketInbound () method by yourself.
This method can be used to listen to events. There are two required methods:
1. protected void onBinaryData (InputStream inStream );
Second, protected void onTextData (Reader reader );
When WebSocket is enabled or disabled, if you want to receive a notification, simply rewrite the onOpen () method and onClose () method.
@Overrideprotected void onOpen(WsOutbound outbound);@Overrideprotected void onClose(int status);
Write Data to the client
The StreamInbound implementation class must be available. It will reference the sender component WsOutbound and can be obtained simply by calling it:
myStreamInbound.getWsOutbound()
Binary data can also be sent.
public void writeBinaryData(int b);public void writeBinaryMessage(ByteBuffer msgBb);
Or send text data to the client.
public void writeTextData(char c);public void writeTextMessage(CharBuffer msgBb);
Note: These methods are mutually exclusive. Do not call two methods at the same time to expect both binary data and text data to be sent.
Disable Client Connection
There are two ways to close the channel: clean and not clean. The clean method means that the handshake protocol has been completed through TCP. The not clean method means that the TCP connection is disconnected and is closed before the handshake.
Implementation of jargery WebSocket
The following is a sequence diagram of the implementation of jargery WebSocket: