Java socket. io combined with node. js

Source: Internet
Author: User

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.

Related Article

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.