服务端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...');
* 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...');
Node.js 实现WebSocket一对一即时聊天应用

本文展示了如何使用Node.js创建一个WebSocket服务器,并实现客户端连接,通过在连接请求时传递用户标识来实现实时一对一聊天功能。服务端监听连接,接收消息,并根据消息中的目标用户ID将消息转发给指定客户端。客户端则发送包含用户信息和内容的JSON消息给服务器,并接收来自服务器的消息。该示例提供了一种避免群发,确保消息精准送达的方法。
最低0.47元/天 解锁文章
1060

被折叠的 条评论
为什么被折叠?



