WebSocket and message push, WebSocket message push
In B/S-structured software projects, sometimes the client needs to obtain server messages in real time, but the default HTTP protocol only supports the request response mode. This can simplify the Web server and reduce the burden on the server, the response speed is accelerated because the server does not need to establish a communication link with the client for a long time, but it is not easy to directly complete the Real-Time Message push function, such as chat rooms, background information prompts, and real-time data update functions. However, this function is required through polling, Long polling, persistent connections, Flash Socket, and WebSocket defined in HTML5.
I. Socket Introduction
Socket, also known as "Socket", usually sends a request to or responds to a network request through "Socket. The original English meaning of Socket is "hole" or "Socket", which serves as a UNIX process communication mechanism. Socket enables network communication between applications.
<! DOCTYPE html>
JSR356 defines the WebSocket specification, which is implemented in Tomcat 7. The JSR356 WebSocket specification uses the javax. websocket. * API. A common Java object (POJO) can use the @ ServerEndpoint annotation as the WebSocket server endpoint.
@ ServerEndpoint ("/push") public class EchoEndpoint {@ OnOpen public void onOpen (Session session) throws IOException {// the following code is omitted ...} @ OnMessage public String onMessage (String message) {// the following code is omitted ...} @ Message (maxMessageSize = 6) public void receiveMessage (String s) {// the following code is omitted ...} @ OnError public void onError (Throwable t) {// the following code is omitted ...} @ OnClose public void onClose (Session session, CloseReason reason) {// the following code is omitted ...}}
The simple code above sets up a WebSocket server. The annotation endpoint of @ ServerEndpoint ("/push") indicates that the WebSocket server runs in ws: // [Server IP address or domain name]: [Server port]/project/push access endpoint. The client browser can initiate an HTTP persistent connection to the WebSocket client API.
The class annotated with ServerEndpoint must have a common non-parameter constructor. The @ onMessage annotation Java method is used to receive incoming WebSocket information, which can be in text format, it can also be in binary format.
OnOpen is called when a new connection is established at this endpoint. The parameter provides more details about the other end of the connection. Session indicates the other end of the WebSocket endpoint connection. It can be understood as similar to HTTPSession.
OnClose is called when the connection is terminated. The closeReason parameter can encapsulate more details, such as why a WebSocket connection is closed.
For more advanced customization, such as @ Message annotation, The MaxMessageSize attribute can be used to define the maximum Message byte limit. In the example program, if more than 6 bytes of information are received, report errors and close connections.
Package action; import javax. websocket. closeReason; import javax. websocket. onClose; import javax. websocket. onError; import javax. websocket. onMessage; import javax. websocket. onOpen; import javax. websocket. session; import javax. websocket. server. pathParam; import javax. websocket. server. serverEndpoint; // ws: // 127.0.0.1: 8087/Demo1/ws/Zhang San @ ServerEndpoint ("/ws/{user}") public class WSServer {private String currentUser; // run @ OnOpen public void onOpen (@ PathParam ("user") String user, Session session) {currentUser = user; System. out. println ("Connected... "+ session. getId ();} // run @ OnMessage public String onMessage (String message, Session session) {System. out. println (currentUser + ":" + message); return currentUser + ":" + message;} // run @ OnClose public void onClose (Session session, CloseReason closeReason) when the connection is closed) {System. out. println (String. format ("Session % s closed because of % s", session. getId (), closeReason);} // when a connection error occurs, run @ OnError public void onError (Throwable t) {t. printStackTrace ();}}
Path parameters in the url, and the method for responding to the request is automatically mapped.
V. Test Run
Vi. Summary and message push framework
Socket is widely used in communications between applications. If you need to be compatible with earlier versions of browsers, it is recommended to use reverse ajax or persistent connections; websocket can be directly used if it is a mobile client or non-modern browser is not required. It is not recommended to use Flash to push messages because it depends on plug-ins and does not support messages on mobile phones. There are also encapsulated plug-ins for reverse ajax, such as "Pushlet"
6.1. Open-source Java Message push framework Pushlet
Pushlet is an open-source Comet framework. Pushlet uses the observer model: the client sends requests and subscribes to events of interest. The server assigns a session ID to each client as a tag, the event SOURCE sends new events to the subscriber's event queue in multicast mode.
Source Code address: https://github.com/wjw465150/Pushlet
Pushlet is a comet implementation: Under the Servlet mechanism, data is pushed directly from the Java object on the server to the (dynamic) HTML page without the help of Java applet or plug-in. It allows the server to periodically update the client's web pages, which is inconsistent with the traditional request/response method. The browser client is compatible with JavaScript1.4 or later browsers (such as InternetExplorer and FireFox) and uses JavaScript/DynamicHTML features. The underlying implementation uses a servlet to connect to the browser where JavaScript is located through Http and push data to the latter.
6.2. Open-source DotNet message push framework SignalR
SignalR is a class library under ASP. NET. It can implement real-time communication in ASP. NET Web projects. Establish a Socket connection between the Web page and the server. When WebSockets is available (Html5 is supported by the browser), SignalR uses WebSockets. If not, SignalR uses long polling to ensure the same effect.
Official Website: http://signalr.net/
Source code: https://github.com/SignalR/SignalR
VII. Code download 7.1. server-side code and client code download implemented in Java
Click to download the server code
Click to download client code
7.2 DotNet server-side manual connection for code download
Click to download the DotNet server manual connection implementation code
7.3. Use the SuperWebSocket third-party library in DotNet to download code
Click to download the code using the SuperWebSocket third-party library under DotNet