前言
- node.js是没有提供内置的websocket模块,下载第三方包ws模块来完成
- 注意的是这个模块好像在断开连接这一块是有点问题,需要自己补充代码
- 通过内置url模块解决路径参数-逻辑代码解决断开连接问题-方便扩展业务需求
- 可以不用-但不能没有这些
代码实现
1.下包
npm install ws
2.参考代码
// 第三方包ws const websocket = require("ws"); // 内置url模块-处理websocket路径参数 const url = require("url"); // 注释 // 前端使用-参考主页文章uni-app使用websocket // sendmessage方法是前端的 // usertype代表类型(5-断开连接/1-发送消息等等-自定义) // 断开连接数据格式 // sendmessage(json.stringify({ // usertype:'5', // moblietype:'用户id' // })) // 创建websocket服务器,监听端口9000 const wss = new websocket.server({ port: 9000 }); // 假设ip是 - 192.168.2.22 // 此时websocket前端连接地址就是 // ws://101.43.100.203:3010:9000?userid=用户id // 存储所有连接 // 方便断开连接 var connections = new set(); wss.on("connection", function connection(ws, req) { // 使用url模块-接收前端发来的userid(路径参数) const parameters = url.parse(req.url, true).query; const userid = parameters.userid; // 用户id+ws实例存入 connections.add({ id: userid, instantiation: ws, }); // 请求头信息-如果是uni-app(app端-传递header-可以打印)- 参考uni-app文档websocket // console.log("请求头信息", req.headers); console.log("客户端连接成功!"); // 接收来自客户端的消息 ws.on("message", function incoming(getmessage) { console.log("客户端: %s", json.parse(getmessage)); // 传递字符串文字-自取 // console.log("客户端: %s", getmessage); // const clientmsg = buffer.from(getmessage.msg, "hex"); let data = json.parse(getmessage); // 断开websocket连接-参考上方注释数据格式 if (data.usertype == 5) { console.log("用户id-断开连接", userid); for (const connection of connections) { if (connection.id == data.moblietype) { // 关闭删除连接池某个websocket连接 connection.instantiation.close(); connections.delete(connection); } } return; } }); });
总结
经过这一趟流程下来相信你也对 node.js项目-创建websocket模块 有了初步的深刻印象,但在实际开发中我 们遇到的情况肯定是不一样的,所以我们要理解它的原理,万变不离其宗。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论