[reproduced] using Node.js+socket.io to build a real-time messaging system

Source: Internet
Author: User
Tags emit

When developing Web applications, there is often a need for messages to be received. For example, the background processing of a task, need to inform users and so on. A simple approach is to use Ajax polling. This brings the problem one is inefficient, the second is that the message is not enough to reach real-time. Another way is to use WebSocket to receive messages, but unfortunately IE does not support this approach. The following is a proposal that can receive both real-time messages and compatible with a variety of browsers, that is Node.js+socket.io.

The asynchronous non-blocking model of node. JS, which makes message push very appropriate. Socket.io is responsible for blocking browser differences, which will selectively use the following ways to establish connections: WebSocket, Flash sockets, Ajax long polling, JSONP polling ... In short, developers no longer have to consider browser compatibility issues.

Code writing aspect, is also relatively simple, basically as long as the corresponding event, write code.

Web page:

<script src= "Http://10.1.164.103:8080/socket.io/socket.io.js" ></script>
<script>
var socket = io.connect (' 10.1.164.103:8080 ');

Socket.emit (' join ', {
Send user Name

Username: ' Test ',
});

Listening messages

Socket.on (' message ', function (data) {
Business processing after receiving a message

...
});

</script>

Server-side, which implements the HTTP request received from PHP, and then pushes the message to the browser's function. Note that a user may open more than one window, so it is necessary to put a link created by the same user into the same room and broadcast the message in the room when the message needs to be pushed.

var host = 10.1.164.103;
var port = 8080;

var http = require (' http ');
var express = require (' Express ');
var app = Express ();

var server = Http.createserver (APP);

Listening port

Server.listen (port, host);
Console.log (' Server running at/http ' + ' + ': ' + port + '/');

App.get ('/', function (req, res) {
if (req.query.name! = undefined && req.query.msg! = undefined) {

The message is broadcast in the room (in case a user opens multiple windows)

Io.sockets.in (Req.query.name). Emit (' message ', {code:0, data:req.query.msg});

}

Res.end ();
});


var io = require (' Socket.io '). Listen (server);

var connectionlist = {};

Listen for all connections to the server.
Io.sockets.on (' Connection ', function (socket) {
Connectionlist[socket.id] = {Socket:socket};
Socket.on (' Join ', function (data) {
if (data.username! = undefined) {

Add a room named after the user name (in case a user opens multiple windows)

Socket.join (Data.username);
Connectionlist[socket.id].username = Data.username;

}

});

Listening for disconnection
Socket.on (' Disconnect ', function () {
if (connectionlist[socket.id].username! = undefined) {

Leave the room
Socket.leave (Connectionlist[socket.id].username);
}
Delete Connectionlist[socket.id];
});
});

Listen for interrupt signals to achieve some special functions

Process.on (' SIGHUP ', function () {
....
});

So far, we have implemented a simple message push demo. Actual business use, you can add login authentication, log module and other functions, improve the message push service.

[reproduced] using Node.js+socket.io to build a real-time messaging system

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.