Socketio server push and socketio server push

Source: Internet
Author: User
Tags maven central

Socketio server push and socketio server push
If the interviewer asks you: how to display the server data on a browser from time to time? I think many people will answer the question of using Ajax technology to access a resource on a regular basis. That's right. Ajax can be used, but what the interviewer wants is definitely not the answer. Because frequent access to Ajax causes too much pressure on the server, it is not recommended in most cases. The answer the interviewer wants is to push the server data to the browser, So that you only need to maintain a long link.

Socket. io can realize data from time to time push, socket. io (Official Website: http://socket.io/) is a cross-platform, a variety of connection mode automatic switch from time to time engine. It should be noted that socket. io. js can only implement the client function, but also the server implementation to truly push data. The official example provided by socket. io is implemented using node. js on the server side. I think many others are unfamiliar with node. js (me too ). The socket. io server can be implemented in multiple languages. It should be said that only the socket protocol can be supported.

The following example shows the server implementation of two java languages and the example of using it. The sample content is very simple, that is, a coordinate (including the x and y values) is randomly generated on the server end, and then pushed to the browser for display. I want to push a coordinate value. It is not a problem to push other data.


The first implementation is netty-socketio. The coordinates are com. corundumstudio. socketio: netty-socketio: 1.7.3 (gradle). If maven is used, the coordinates are:


<groupId>com.corundumstudio.socketio</groupId><artifactId>netty-socketio</artifactId><version>1.7.3</version>

A. server code:

Public class Server {private static List <SocketIOClient> clients = new ArrayList <SocketIOClient> (); // used to save all clients public static void main (String [] args) throws Exception {Configuration configuration = new Configuration (); configuration. setHostname ("127.0.0.1"); // set the host name configuration. setPort (8082); // set the listening port SocketIOServer server = new SocketIOServer (configuration); // create the server Object server according to the configuration. addConnectListener (new ConnectListener () {// Add the client connection listener @ Overridepublic void onConnect (SocketIOClient client) {System. out. println ("connected: SessionId =" + client. getSessionId (); clients. add (client); // save client}); server. start (); System. out. println ("server started"); Timer timer = new Timer (); timer. schedule (new TimerTask () {@ Overridepublic void run () {Random random = new Random (); for (SocketIOClient client: clients) {client. sendEvent ("pushpoint", new Point (random. nextInt (100), random. nextInt (100); // push once every second }}, 1000,100 0); Object object = new Object (); synchronized (object) {object. wait ();}}}

B. Point class:

public class Point {private int x;private int y;public Point(int x, int y) {this.x = x;this.y = y;}//getter,setter}

C.html page:

<! DOCTYPE html> 

The second implementation is socketio-netty (the above one is netty-socketio). This implementation does not seem to exist in the maven Central Library. The project is hosted on google code and the Project address is: compile.
A. server code:

Public class Server2 {private static List <IOClient> clients = new ArrayList <IOClient> (); public static void main (String [] args) throws Exception {SocketIOServer ioServer = new SocketIOServer (new IOHandlerAbs () {@ Overridepublic void OnShutdown () {System. out. println ("shut down") ;}@ Overridepublic void OnMessage (IOClient client, String eventName) {System. out. println ("receive message, eventName =" + eventName) ;}@ Overridepublic void OnDisconnect (IOClient client) {System. out. println ("disconnect"); System. out. println ("disconnect") ;}@ Overridepublic void OnConnect (IOClient client) {System. out. println ("connect"); clients. add (client) ;}}, 8088); ioServer. start (); System. out. println ("server started"); Timer timer = new Timer (); timer. schedule (new TimerTask () {@ Overridepublic void run () {Random random = new Random (); String data = "{\" x \ ":" + random. nextInt (100) + ", \" y \ ":" + random. nextInt (100) + "}"; BASE64Encoder encoder = new BASE64Encoder (); data = encoder. encode (data. getBytes (); for (IOClient client: clients) {client. send (formatMessage (data) ;}}, 1000,100 0); Object object = new Object (); synchronized (object) {object. wait () ;}} private static String formatMessage (String data) {return String. format ("5 ::{\" % s \ ": \" % s \ ", \" % s \ ": [\" % s \ "]}", // socket. io string format "name", "push", // event name "args", data // carried data );}}

It must be noted that this implementation cannot send an object like the previous implementation, but can only send one string, and the string cannot contain double quotation marks (maybe there are other special characters ). The data format we use during the push process is probably JSON, so there must be double quotation marks, so here we adopt the method of BASE64 encoding for the data to be sent, then, the client decodes the desired data.

B .html page:

<! DOCTYPE html> 

In the first example, the socket. io version is 1.0.6, and the second version is 0.9.6. These two Server implementations are based on the netty framework, but I personally think the first one is better, saving the coding process and providing a higher degree of encapsulation.

The sample code project is hosted on GitHub and built with gradle at https://github.com/x?fjpk/socketio-test.
You just need to extract it to run.

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.