如何查找网站死链,最好的外贸网站建设,网络优化工程师需要学什么,网页设计叫什么如何使用websocketnode.js实现pc后台与小程序端实时通信 一、使用node.js创建一个服务器二、pc后台连接ws三、小程序端连接ws四、实现效果 实现功能:实现pc后台与小程序端互发通信能够实时检测到 一、使用node.js创建一个服务器
1.安装ws依赖
npm i ws2.创建index.js
const… 如何使用websocketnode.js实现pc后台与小程序端实时通信 一、使用node.js创建一个服务器二、pc后台连接ws三、小程序端连接ws四、实现效果 实现功能:实现pc后台与小程序端互发通信能够实时检测到 一、使用node.js创建一个服务器
1.安装ws依赖
npm i ws2.创建index.js
const WebSocket require(ws)const wss new WebSocket.Server({ port: 8888 })
const wsList {}
console.log(服务器启动)
wss.on(connection, (ws) {ws.on(message, (message) {const result JSON.parse(message)console.log(接收到的结果, result)// 页面初始化的时候使用wsList将ws进行缓存if (result.message init) {wsList[result.name] ws} else {// 根据name的值来给指定的客户端发送信息const ws wsList[result.name]ws.send(result.message)}})ws.on(close, () {Object.keys(wsList).forEach((item) {// 当websoket关闭的时候要清空对应的wsif (wsList[item].readyState ! 1) {delete wsList[item]}})})
})3.打开终端,启动服务
node index.js二、pc后台连接ws
!DOCTYPE html
html langenheadmeta charsetUTF-8 /meta http-equivX-UA-Compatible contentIEedge /meta nameviewport contentwidthdevice-width, initial-scale1.0 /titleDocument/title/headbodyspanP后台/span/divinput typetext idinput /button idbutton发送/buttonscriptvar ws new WebSocket(ws://localhost:8888)//连接wsws.onopen function () {ws.send(JSON.stringify({ name: PC, message: init }))console.log(已连接)}//接收ws.onmessage async function (mes) {console.log(pc接收到的消息, mes)}let Btn document.getElementById(button)//发送事件Btn.onclick function () {let ipt document.querySelector(#input)let obj {name: WX,message: ipt.value,}//需转成字符串ws.send(JSON.stringify(obj))}/script/body
/html三、小程序端连接ws 这里是手动点击连接按钮,发起的websocket连接,可自行更改到其他合适的地方连接websocket 1.创建两个按钮,连接按钮,发送按钮
view clickconnect()连接/view
view clicksendSocket()发送/view2.定义事件,连接ws
//发送ws
sendSocket() {console.log(发送wx)uni.sendSocketMessage({data: JSON.stringify({name: PC,message: wx})})
},
//连接ws
connect() {if (this.connected || this.connecting) {uni.showModal({content: 正在连接或者已经连接请勿重复连接,showCancel: false,})return}this.connecting trueuni.showLoading({title: 连接中...,})uni.connectSocket({url: ws://localhost:8888,success(res) {// 这里是接口调用成功的回调不是连接成功的回调请注意console.log(uni.connectSocket success, res)},fail(err) {// 这里是接口调用失败的回调不是连接失败的回调请注意console.log(uni.connectSocket fail, err)},})//监听WebSocket连接打开事件uni.onSocketOpen((res) {console.log(监听中)if (this.pageVisible) {this.connecting falsethis.connected trueuni.hideLoading()uni.showToast({icon: none,title: 连接成功,})console.log(onOpen, res)uni.sendSocketMessage({data: JSON.stringify({name: WX,message: init})})}})uni.onSocketError((err) {console.log(onError, err)if (this.pageVisible) {this.connecting falsethis.connected falseuni.hideLoading()uni.showModal({content: 连接失败可能是websocket服务不可用请稍后再试,showCancel: false,})}})uni.onSocketMessage((res) {console.log(接收到了通知, res)if (this.pageVisible) {this.msg res.dataconsole.log(onMessage, res)}})uni.onSocketClose((res) {if (this.pageVisible) {this.connected falsethis.msg console.log(onClose, res)}})
},
四、实现效果