使用Nodejs做websocket服务端与客户端实现即时聊天

服务端nodejs:/**
* Created by jhf on 14-10-13.
*/
var cons = new Array();
var userArray = new Array();
var WebSocketServer = require('ws').Server,
    wss = new WebSocketServer({port:8080});

wss.on('connection',function(ws){
    //从头中取出客户端标示userid,当然也可以得到客户端的ip地址
    var userId = ws.upgradeReq.headers['userid'];
    console.log('new connection successfully userId:'+userId);
    cons.push(ws);
    userArray.push(userId);
    ws.on('message',function(message){
        console.log(message);
        for (var i=0; i<cons.length;i++) {
            //判断userid是否为toUserId(发给指定的客户端)
            var msgObj = JSON.parse(message);
            if (userArray[i] == msgObj.toUserId) {
                cons[i].send(message);
                break;
            }
        }
    });
    ws.on('close',function(){
        for (var i=0;i<cons.length;i++){
            if (cons[i]==ws)cons.splice(i,1);
        }
    });
});

console.log('websocket-server running...');

客户端nodejs:
/**
* Created by jhf on 14-10-13.
*/
var WebSocket = require('ws')
    ,Options = require('options');

var options = new Options({"headers":{}});
options = {
    "headers":{"userid":"abc"}
};
var ws = new WebSocket('ws://127.0.0.1:8080',options);

ws.on('open',function(ss){
    var obj = {
        "toUserIconUrl": "/api/getPicture/53c9e22cce37989659b24852",
        "toUserName": "Fred",
        "toUserId": "54237cb58c29a38f44362082",
        "content": "测试消息",
        "fromUserIconUrl": "/api/getPicture/53c0b7337a4dd8f77549838e",
        "fromUserName": "Jin",
        "fromUserId": "538aacd78016832f19000062",
        "contentType": "text",
        "time": (new Date()).getTime()
    };
    var str = JSON.stringify(obj);
    console.log(str);
    ws.send(str);

});
ws.on('message',function(message){
   console.log('received: %s',message);
});

基本原理:
1,客户端连接到服务端的时候在header里面加入用户标示userid,用来判断哪个客户端连接到了服务端
2,服务端从header里面获取userid,在消息体中判断需要发送给哪个客户端(toUserId与header里面相等),将客户端发来的消息发送到指定客户端(网络上都是群发聊天室的例子居多,一对一聊天的很难找到)

另外,header中的id可以加密,消息内容也可以加密后发送,header是在websocket建立socket连接之前握手的时候指定的,一些加密的协议会在握手的时候进行处理,防止非法客户端连入服务端

你可能感兴趣的:(websocket,nodejs)