Socket. io, user node. as a server, js is used for Synchronous synchronization. For example, when a user logs on to a website, multiple windows of the browser are displayed after logon.
First, install socket. io and the required modules, reference the js package of socket. io in the project, and build the socket. io class using java code. For details about this class, refer to https://github.com/gottox/socket.io-java-client.
You also need to install node. js. Create socketserver. js in the project file location and run node. js to learn how to install and run node. js.
Socketserver. js content depends on your own business needs, but it should be noted that each page request is unique, even if the same key is used to record the socket, therefore, an array is also required to record, otherwise, only one page request can be processed,
For example, var users ={}; // the function that stores the user group after Logon
Socket. on ('inituser', function (key ){
Var sockets = users [key];
If (sockets ){
Sockets. push (socket );
} Else {
Sockets = [socket];
}
Users [key] = sockets; // multiple page records agree to the client of different pages of the user
});
After successful logon, the notification page is logged on.
// When the user logs on successfully, the system pushes the message to the client prompting that the user logs on successfully.
Socket. on ('Do _ login', function (jsonData) {// capture the data sent by the client named 'do _ login'. If the business needs to, you can extend the callback parameter.
Var jsSockets = users [jsonData. userKey];
If (jsSockets ){
Console. log ('number of jsSockets: '+ jsSockets. length );
For (var I = 0; I <jsSockets. length; I ++ ){
JsSockets [I]. emit ('login _ success ', jsonData. loginResult); // tell the client to connect to the login information of this request. The broadcast attribute is applicable to multiple connections.
}
}
});
OK. This enables synchronous notification between socket. io and node. js.