Real-time data push with node. JS (Socket.io)

Source: Internet
Author: User
Tags emit

At the time of the auction, we need to update the highest price of the current item in real time on the item's auction page. There are many ways to achieve this, such as:

1.setInterval every n seconds to pull data asynchronously (disadvantage: Update not real-time)

2. Ajax polling mode push data (disadvantage: The server needs to repeatedly query the database in the dead loop)

3.websocket Push data (Cons: only browsers that support the HTML5 standard)

A brief introduction to Socket.io

All clients are hung on the Nodejs server via Socket.io (note: Just hang up, don't need any loops because it's event-driven), need to push a message, the server communicates with Nodejs (for example, access to an address), and tells it where to push the message. Nodejs receives a push signal, it transmits the data to the browser in real time via Socket.io. This is actually a one-way road, because the NODEJS server does not have the ability to communicate with PHP, in fact, do not need, the page directly connected to PHP.

And then we'll start thinking.

1. As stated in the brief introduction, the client is first hung on the Nodejs server via Socket.io.

After the user enters the auction page, start connecting to Socket.io, and then store the current client's ' User ID ', ' Auction id ', ' current highest price ', ' socket.id ' in the node. JS global variable Socketuser.

Client

var socket = Io.connect ("Http://demo.xiaocai.name": 339 ") Socket.on (' conn ', function (data) {  var postdata = {' c_id ')   : PageValue.charinfo.c_id,     //user ID        ' c_name ': PageValue.charinfo.c_name,   //user nickname        ' GUID '   : pagevalue.infodata.id,//Auction ID        ' price '  : pagevalue.infodata.max_price,//current highest premium  }  socket.emit (' Login ', postdata,function (result) {     Console.log (' landed successfully ');});  

Service side

var   sio     = require (' Socket.io '); var   express = require (' Express '); var   app  =  Module.export = Express.createserver ();//Initialize var Socketuser = {};io  = Sio.listen (APP); Io.set (' Log level ', 1);// The debug information in the Socket.io is switched off//Listening connection io.sockets.on (' Connection ', function (socket) {    ///Response Connection    io.sockets.emit (' conn '), {text: ' Socketid: ' +socket.id});    Listen for user login and store socket    socket.on (' Login ', function (DATA,FN) {Socketuser[socket.id] = {' c_id ':d ata.c_id, ' GUID ': Data.guid, ' price ':d ata.price, ' socket ': socket};    });   Monitor disconnection    socket.on (' Disconnect ', function () {        console.log ('-Link break [' +socket.id+ '] '-');        Delete socketuser[socket.id];})    ;

read out the highest price of the current auction from the Redis cache, and then traverse the Socketuser collection under the auction, pushing it to the latest price (and updating its high price) if its price is lower than the highest value taken out. Getrediskey is a method of reading Reids The method is posted at the bottom.

var pushprice = function (GUID) {

Console.log ('-Push data [' +guid+ ']-');

Common_func. Getrediskey ("auctionmaxprice-" +guid,function (val) {

if (!val) {

return false;

}

for (var values in Socketuser) {

if (parsefloat (Socketuser[values].price) < val && Socketuser[values].guid = = GUID) {

Socketuser[values].socket.emit (' receive ', {' Nowprice ': val});

Socketuser[values].price = val;

}

}

});

}

3. The client accepts push data

Socket.on (' Receive ', function (maxprice) {

$ (' #NowUserTxt '). html (' ¥ ' +maxprice);

});

Getrediskey is a method of obtaining a Redis cache in a public function, which is posted separately here.

Exports. Getrediskey = function (key,fun) {

if (typeof redis_client = = ' undefined ') {

var Redis = require ("Redis");

Redis_client = Redis.createclient (redisport,redishost);

Redis_client.on ("Error", function (Err) {

Common_func.insertlog ("Error (Redis):" + err);

})

}

Redis_client.get (key, function (err, reply) {

if (Reply) {

Fun (reply.tostring ());

}else{

Fun (false);

Common_func.insertlog (' Error (Redis): Get (' +key+ ') not data ');

}

});

}

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.