nodejs+websocket聊天工具
2021-07-11 23:07
阅读:653
YPE html>
标签:启动 break set lock cli let show pip osi
该聊天工具,使用nodejs起服务,websocket前端页面,聊天工具,,可以有任意多的人数参与聊天,里面的用户ID为模拟ID。
先上图

文件夹结构,

1、安装ws模块,npm install ws
2、web.js文件,是Nodejs后端代码
var WebSocketServer = require(‘ws‘).Server,
wss = new WebSocketServer({ port: 8181 });
//var client1 = null,client2=null,client1Ready = false, client2Ready = false;
var config = {};
var userList = {};
wss.on(‘connection‘, function (ws) {
console.log(‘client connected‘);
ws.on(‘message‘, function (message) {
var data = JSON.parse(message);
console.log(data);
if(data.type == ‘register‘){
console.log("register");
config[data.meID] = {
ID:data.meID,
myNike:data.sendNike,
pipe:ws,
Ready:true
};
userList[data.meID] = {
ID: data.meID,
myNike: data.sendNike
};
refreshList();
}else if(data.type == ‘sendMessage‘){
console.log("send");
sendMessage(data);
}else{
ws.send(JSON.stringify({"error":true}));
}
});
ws.on("close",function(code, reason){
for(var i in config){
if(config[i].pipe === ws){
config[i].Ready = false;
config[i].pipe = null;
delete config[i];
delete userList[i];
refreshList();
break;
}
}
console.log("关闭链接");
});
});
//更新聊天列表
function refreshList(){
for(var i in config){
config[i].pipe.send(JSON.stringify({
‘type‘:‘refreshList‘,
‘list‘:userList
}));
}
}
//更新聊天
function sendMessage(data){
if(config[data.receiveID]){
//对方在线
data.sendNike = userList[data.meID].myNike;
config[data.meID].pipe.send(JSON.stringify(data));
config[data.receiveID].pipe.send(JSON.stringify(data));
}else{
//对方不在线
config[data.meID].pipe.send(JSON.stringify({"error":true}));
}
}
//npm install ws
2、添加客户端client.html
client1 正在链接..在线好友列表
3、添加客户端,client2.html,client3.html,,,只需要修改client1.html中,config的sendNick如图,

4、注意添加jquery文件
5、nodejs启动web.js文件,打开所有.html文件,进行聊天。
nodejs+websocket聊天工具
标签:启动 break set lock cli let show pip osi
原文地址:http://www.cnblogs.com/muamaker/p/7084513.html
文章来自:搜素材网的编程语言模块,转载请注明文章出处。
文章标题:nodejs+websocket聊天工具
文章链接:http://soscw.com/index.php/essay/103899.html
文章标题:nodejs+websocket聊天工具
文章链接:http://soscw.com/index.php/essay/103899.html
评论
亲,登录后才可以留言!