NodeJS + Socket.IO 消息推送
//socket.io var app = require("express")(); var http = require("http").Server(app); var io = require("socket.io")(http); //couchbase var couchbase = require("couchbase"); var cluster = new couchbase.Cluster("couchbase://192.168.1.1"); var bucket = cluster.openBucket("name","pass"); var onlineUsers = {}; var onlineCount = 0; io.on("connection" , function(socket){ socket.on("login" , function(obj){ socket.name = obj.userid; console.log(new Date() + " : 编号" + obj.userid + "员工已登录!"); if(!onlineUsers.hasOwnProperty(obj.userid)){ //onlineUsers[obj.userid] = obj.userid; onlineUsers[obj.userid] = {'c_id':obj.userid,'socket':socket}; onlineCount ++; } }); socket.on("disconnect" , function(){ if(onlineUsers.hasOwnProperty(socket.name)){ var obj = {userid:socket.name}; delete onlineUsers[socket.name]; onlineCount --; console.log(new Date() + " : 编号" + obj.userid+'已登出!'); } }); }); setInterval(function(){ bucket.getMulti([ "Name1" , "Name2" ], function(err, result) { if(err){ console.log(new Date() + " : ERROR : " + err); } else { NodeEmit(result); } }); } , 10 * 1000); function NodeEmit(result){ for(var user in onlineUsers){ _Str_Name1 = result["Name1"].value["content"][user]; //io.emit("cmd" + user.toString() , _Str); onlineUsers[user].socket.emit("cmd" + user.toString() ,_Str_Name1); // if(typeof(result["Name2"].value["content"][user]) != "undefined"){ _Str_Name2 = JSON.stringify(result["Name2"].value["content"][user]); //io.emit("cmd2" + user.toString() , _Str_Name2); onlineUsers[user].socket.emit("cmd2" + user.toString() , Str_Name2); } } } http.listen(8066 , function(){ console.log("listening on *:8066"); });
1、一次从Couchbase 获取多个 document
bucket.getMulti([ "Name1" , "Name2" ], function(err, result) { if(err){ } else{ } });
使用
result["Name1"]
2、解决CPU 占用 100%的问题。
原来是用IO对象直接 emit
var io = require(“socket.io”)(http);
io.emit(“cmd”+userid , _Str);
现在把每个连接的socket保存下来
onlineUsers[obj.userid] = {‘c_id’:obj.userid,‘socket’:socket};
推送时
onlineUsers[userid].socket.emit(“cmd” +user id, _Str);