[Anti-ajax] webSocket realizes real-time push function

Forehead. The day before yesterday, I said that I have time to study the real-time push technology of webSocket. A small function that combines the publish/subscribe function of redis has been implemented with Comet, but it is actually a bit complicated. When I had time today, I learned about webSocket and found that it was not as difficult as I imagined!

But I still have a lot of time to do things with webSocket. There is one made with spring+webSocket, which is a little more complicated (maybe more fault-tolerant and robust?), and finally got stuck on a 404 connection, and the jar package used is spring -websocket-4.2.x.jar and related dependency jar packages. In view of the fact that the examples on the Internet have not been implemented, let's pretend.

Later, with JavaEE7 (jdk1.7+ support) and webSocket supported by html5, the problem becomes much simpler. Involved jar package: websocket-api-1.x.jar

 

Client:

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>pubsub test</title>
	
	<script type="text/javascript">
		var socket = null;
		$(function() {
			was the web socket;
//Consider various browser compatibility issues
            if ('WebSocket' in window) {
                websocket = new WebSocket("ws://localhost:8080/amp/socket/webSocketServer");
            } else if ('MozWebSocket' in window) {
                websocket = new MozWebSocket("ws://localhost:8080/amp/socket/webSocketServer");
            } else {
                websocket = new SockJS("http://localhost:8080/amp/sockjs/webSocketServer");
            }
//The operation send operation after the connection with the server is successful must have the server to respond          
            websocket.onopen = function (evnt) {
            	var data = {appId:'hx', status:'s'};
            	websocket.send(JSON.stringify(data));//Try to send json parameters to the server, which is also common in projects
            	$("#showMsg").append("Connection succeeded!<br/>");
            };
// Callback after receiving the data returned by the server
            websocket.onmessage = function (evnt) {
                $("#showMsg").append("(<font color='red'>"+evnt.data+"</font>)<br/>");
            };
//Connection failed callback
            websocket.onerror = function (evnt) {
            };
// Caused by server shutdown
            websocket.onclose = function (evnt) {
            	$("#showMsg").append("Connection closed!<br/>");
            }
		});
	</script>
</head>
<body>
	<div id="showMsg" style="border: 1px solid; width: 500px; height: 400px; overflow: auto;"></div>
</body>

 Server:

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import net.sf.json.JSONObject;

@ServerEndpoint("/socket/webSocketServer")
public class ScrollInfoHandler {
//Receive the client's request
	@OnMessage
	  public void onMessage(String message, Session session)
	    throws IOException, InterruptedException {
	   
	    System.out.println("Received: " + message);
	    
	    Map<String, String> params = JSONObject.fromObject(message);
	    
	    // Send the first message to the client
	    session.getBasicRemote().sendText("return params after handled: "
	    		+ params.get("appId").toUpperCase() + ", " + params.get("status").toUpperCase());
	   
	    // Send 3 messages to the client every 5 seconds
	    int sentMessages = 0;
//Simulate push data
	    while(true){
	      Thread.sleep(2000);
	      session.getBasicRemote().
	        sendText("This is an intermediate server message. Count: "
	          + Math.random());
	    }
	   
	  }
//After connecting to the client successfully	   
	  @OnOpen
	  public void onOpen() {
	    System.out.println("Client connected");
	  }
//After the client is closed	 
	  @OnClose
	  public void onClose() {
	    System.out.println("Connection closed");
	  }
	
}

 If you want to combine with redis publish and subscribe, it is very simple: start the thread of the subscription channel in the onOpen function of the server, and the thread that regularly checks the size of the queue, and in the onMessage function perform timing pop data from the queue and send, and write in onClose Just stop the logic of threads and empty queues.

 

Let's test the effect below!

Start the project, open this client page, and first observe the console print:

Client connected

Received: {"appId":"hx","status":"s"}

Indicates that the server has been connected to the client and has received the passed parameters.

Observe the client page, you will find: (at some point)



 The client is constantly refreshed, and it also receives the data sent by the server after processing the parameters.

If the client is closed, the server console will print: Connection closed

If the server is closed, the client will look like this:



 Description, to achieve the effect after the response server is closed.

 

The above is just a very simple push example. To be applied to actual projects, it is necessary to continuously improve the code to improve its robustness. But at least for me, the server-side active push technology is finally no longer so mysterious and confusing. It can be adopted in places with higher real-time requirements in the future, and finally breaks through the ajax method.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326668069&siteId=291194637