最近给一个客户做了一个聊天,所以就用NodeJS做了一个
原理就是用户第一次进入后,记录它的ID和该用户的ws
等有人发数据的时候,就去查ID,然后找到ID对应的ws,进行消息发送
核心就是用数组做了一个类似python字典的东西
var WebSocketServer = require(‘ws‘).Server,wss = new WebSocketServer({ port: 8888 });var AllUserData = new Array();wss.on(‘connection‘, function (ws) { ???console.log(‘client connected‘); ???ws.on(‘message‘, function (message) { ???????console.log(message); ???????Temp = JSON.parse(message); ???????if(CheckIsNew(Temp)) ???????{ ???????????AllUserData.push({ ???????????????‘id‘:Temp.ID, ???????????????‘ws‘:ws ???????????} ???????????); ???????????console.log(AllUserData); ???????} ???????else ???????{ ???????????for(var i=0;i<AllUserData.length;i++) ???????????{ ???????????????if(Temp.ID == AllUserData[i][‘id‘]) ???????????????{ ???????????????????if(Temp.Data != "userregister") ???????????????????{ ???????????????????????AllUserData[i][‘ws‘].send(Temp.ID+Temp.Data); ???????????????????????break; ???????????????????} ???????????????} ???????????} ???????} ???});});function CheckIsNew(Temp){ ???for(var i=0;i<AllUserData.length;i++) ???????{ ???????????if(Temp.ID == AllUserData[i][‘id‘]) ???????????{ ???????????????return false; ???????????} ???????} ???????return true;}
下面是一个简单的连接Demo
<html> ???<head> ???????<title>GetData</title> ???</head> ???<body> ???????<textarea cols=40 rows=20 id="output"></textarea> ???????<button width=200 height=200 onclick="Sent(2,111)">Sent1</button> ???????<button width=200 heigh=200 onclick="Sent(1,222)">Sent2</button> ???</body> ???<script src="https://www.gstatic.com/firebasejs/4.13.0/firebase.js"></script> ???<script src="websocket.js"></script> ???<script> ???var s= new MyWebSocket(success,fial,getmes); ???s.OPen("ws://127.0.0.1:8888"); ???register(1); ???register(2); ???function Sent(friendid,Data) ???{ ???????var Json = { ???????????‘ID‘:friendid, ???????????‘Data‘:Data ???????}; ???????s.Sent(JSON.stringify(Json)); ???} ???function register(id) ???{ ???????var Json = { ???????????‘ID‘:id, ???????????‘Data‘:"userregister" ???????}; ???????s.Sent(JSON.stringify(Json)); ???} ???function start() ???????{ ???????} ???????function success() ???????{ ???????????document.getElementById("output").value = "success"; ???????} ???????????????function fial(a) ???????{ ???????????????????} ???????????????function getmes(a) ???????{ ???????????document.getElementById("output").value = a; ???????} ???</script></html>
里面用到的websocket.js,可以看我前面的博客,当然也可以直接自己写
[NodeJS]NodeJS基于WebSocket的多用户点对点即时通讯聊天
原文地址:https://www.cnblogs.com/lee-li/p/8930902.html