实现了基于socket.io的web即时聊天,真正的运用推方式获取实时消息。服务器是基于nodejs。io.on('connection', function (socket) {
socket.emit('news',{ hello: 'Session ' socket.id });
var socketId = socket.id;
connectionList[socketId] = {authentication:false};
async.auto({
authentication: function (callback) {
socket.on('authentication', function (data) {
connectionList[socketId].authentication = true;
socket.emit('result' , '1');
callback();
});
},
nickname: ['authentication', function(callback,results) {
socket.on('set nickname', function (name) {
if(connectionList[socketId].authentication) console.log("验证通过");
else {
console.log("验证不通过");
socket.disconnect();
callback("ERROR");
return;
}
connectionList[socketId].name = name;
socket.emit('news' , { hello: 'hi, ' name '!' });
socket.join(name);
callback("OK");
});
}]
}, function(err, results) {
});
socket.on('message', function (msg) {
console.log('Message Received: ', msg);
var nickname = connectionList[socketId].name;
socket.broadcast.emit('message', 'From ' nickname ': ' msg);
});
socket.on('disconnect', function () {
var log = require("./log").logger("index");
log.info('a connection was disconnect:' socketId);
console.log('a connection was disconnect:' socketId);
});
});
评论