websocket 服务搭建
链接过程
前端
1、CREATED WEBSOCKE
2、ONOPEN
3、ONMESSAGE
服务端
1、收到request
2、给客户端发送消息,生成id
//msg
{
type: "id",
id: Date.now()
}
前端
1、收到messge,type为id,
2、给服务端发送消息type=username的消息,携带id
// clientID = msg.id
var msg = {
name: document.getElementById("name").value,
date: Date.now(),
id: clientID,
type: "username"
};
服务端
1、收到type为username的msg
2、设置connect.username = msg.name;
3、广播给其他用户消息 type: "userlist",
var userListMsg = {
type: "userlist",
users: []
};
4、服务端发送usename消息
if (sendToClients) {
var msgString = JSON.stringify(msg);
var i;
for (i=0; i<connectionArray.length; i++) {
console.log(102, msgString);
connectionArray[i].sendUTF(msgString);
}
}
前端
1、 前端收到type=userlist的message,渲染用户列表 2、 前端收到type=username的message,渲染聊天室的登录消息
User lili signed in at 上午10:03:24
User hanmei signed in at 上午10:03:24
User lili signed in at 上午10:03:24
User hanmei signed in at 上午10:03:24
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 | /** * @Description: In User Settings Edit * @Author: your name * @Date: 2019-09-02 16:17:14 * @LastEditTime: 2019-09-04 10:16:54 * @LastEditors: Please set LastEditors */ "use strict" ; var https = require( 'http' ); // var fs = require('fs'); var WebSocketServer = require( 'websocket' ).server; var connectionArray = []; var nextID = Date.now(); var appendToMakeUnique = 1; // var httpsOptions = { // key: fs.readFileSync("/etc/pki/tls/private/mdn-samples.mozilla.org.key"), // cert: fs.readFileSync("/etc/pki/tls/certs/mdn-samples.mozilla.org.crt") // }; /** * @description 创建http server * */ var httpsServer = https.createServer( function (request, response) { console.log(( new Date()) + " Received request for " + request.url); response.writeHead(404); response.end(); }); httpsServer.listen(6502, function () { console.log(( new Date()) + " Server is listening on port 6502" ); }); console.log( "***CREATING WEBSOCKET SERVER" ); /** *@description 创建WebSocketServer * */ var wsServer = new WebSocketServer({ httpServer: httpsServer, autoAcceptConnections: false }); console.log( "***CREATED" ); function originIsAllowed(origin) { // This is where you put code to ensure the connection should // be accepted. Return false if it shouldn't be. return true ; } function isUsernameUnique(name) { var isUnique = true ; var i; for (i=0; i<connectionArray.length; i++) { if (connectionArray[i].username === name) { isUnique = false ; break ; } } return isUnique; } function getConnectionForID(id) { var connect = null ; var i; for (i=0; i<connectionArray.length; i++) { if (connectionArray[i].clientID === id) { connect = connectionArray[i]; break ; } } return connect; } function makeUserListMessage() { var userListMsg = { type: "userlist" , users: [] }; var i; // Add the users to the list for (i=0; i<connectionArray.length; i++) { userListMsg.users.push(connectionArray[i].username); } return userListMsg; } function sendUserListToAll() { var userListMsg = makeUserListMessage(); // console.log(111, userListMsg); var userListMsgStr = JSON.stringify(userListMsg); var i; // console.log(connectionArray); for (i=0; i<connectionArray.length; i++) { //立即将指定的字符串作为UTF-8 WebSocket消息发送给远程对等体 console.log(100, userListMsgStr); connectionArray[i].sendUTF(userListMsgStr); } } console.log( "***CRETING REQUEST HANDLER" ); wsServer.on('request ', function(request) { console.log("Handling request from " + request.origin); if (!originIsAllowed(request.origin)) { request.reject(); console.log("Connection from " + request.origin + " rejected."); return; } // Accept the request and get a connection. var connection = request.accept("json", request.origin); // Add the new connection to our list of connections. console.log((new Date()) + " Connection accepted."); connectionArray.push(connection); // console.log(connectionArray); // Send the new client its token; it will // respond with its login username. connection.clientID = nextID; // console.log(connection.clientID); nextID++; var msg = { type: "id", id: connection.clientID }; console.log(99, msg); connection.sendUTF(JSON.stringify(msg)); /** * @description 接收消息 */ connection.on(' message ', function(message) { console.log("***Received MESSAGE*******", message); if (message.type === ' utf8 ') { // console.log("Received Message: " + message.utf8Data);ß // Process messages var sendToClients = true; msg = JSON.parse(message.utf8Data); // console.log(1111,msg); var connect = getConnectionForID(msg.id); /** * @description 接收到的数据 */ switch(msg.type) { // Public text message in the chat room case "message": msg.name = connect.username; msg.text = msg.text.replace(/(<([^>]+)>)/ig,""); break; /** * @description 登录的操作,通知其他人展示 */ // Username change request case "username": var nameChanged = false; var origName = msg.name; while (!isUsernameUnique(msg.name)) { msg.name = origName + appendToMakeUnique; appendToMakeUnique++; nameChanged = true; } if (nameChanged) { var changeMsg = { id: msg.id, type: "rejectusername", name: msg.name }; console.log(101,changeMsg); connect.sendUTF(JSON.stringify(changeMsg)); } connect.username = msg.name; sendUserListToAll(); break; } // Convert the message back to JSON and send it out // to all clients. /** * @desciption 发送给客户端消息 */ if (sendToClients) { var msgString = JSON.stringify(msg); var i; for (i=0; i<connectionArray.length; i++) { console.log(102, msgString); connectionArray[i].sendUTF(msgString); } } } }); // Handle the WebSocket "close" event; this means a user has logged off // or has been disconnected. /** * @description 关闭socket */ connection.on(' close', function (connection) { // console.log(connectionArray); console.log(JSON.stringify(connection)); console.log(( new Date()) + " Peer " + connection.remoteAddress + " disconnected." ); connectionArray = connectionArray.filter( function (el, idx, ar) { // console.log(el.connected); return el.connected; }); sendUserListToAll(); // Update the user lists // console.log(connectionArray); }); }); console.log( "***REQUEST HANDLER CREATED" ); |
参考文章
你要觉得这篇文章比较好,记得点推荐!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通