實(shí)現(xiàn)功能:實(shí)現(xiàn)pc后臺(tái)與小程序端互發(fā)通信能夠?qū)崟r(shí)檢測(cè)到
一、使用node.js創(chuàng)建一個(gè)服務(wù)器
1.安裝ws依賴
npm i ws
2.創(chuàng)建index.js
const WebSocket = require('ws')
const wss = new WebSocket.Server({ port: 8888 })
const wsList = {}
console.log('服務(wù)器啟動(dòng)')
wss.on('connection', (ws) => {
ws.on('message', (message) => {
const result = JSON.parse(message)
console.log('接收到的結(jié)果', result)
// 頁面初始化的時(shí)候,使用wsList將ws進(jìn)行緩存
if (result.message === 'init') {
wsList[result.name] = ws
} else {
// 根據(jù)name的值來給指定的客戶端發(fā)送信息
const ws = wsList[result.name]
ws.send(result.message)
}
})
ws.on('close', () => {
Object.keys(wsList).forEach((item) => {
// 當(dāng)websoket關(guān)閉的時(shí)候,要清空對(duì)應(yīng)的ws
if (wsList[item].readyState !== 1) {
delete wsList[item]
}
})
})
})
3.打開終端,啟動(dòng)服務(wù)
node index.js
二、pc后臺(tái)連接ws
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<span>P后臺(tái)</span>
</div>
<input type="text" id="input" />
<button id="button">發(fā)送</button>
<script>
var ws = new WebSocket(`ws://localhost:8888`)
//連接ws
ws.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')
//發(fā)送事件
Btn.onclick = function () {
let ipt = document.querySelector('#input')
let obj = {
name: 'WX',
message: ipt.value,
}
//需轉(zhuǎn)成字符串
ws.send(JSON.stringify(obj))
}
</script>
</body>
</html>
三、小程序端連接ws
這里是手動(dòng)點(diǎn)擊連接按鈕,發(fā)起的websocket連接,可自行更改到其他合適的地方連接websocket文章來源:http://www.zghlxwxcb.cn/news/detail-771260.html
1.創(chuàng)建兩個(gè)按鈕,連接按鈕,發(fā)送按鈕
<view @click="connect()">連接</view>
<view @click="sendSocket()">發(fā)送</view>
2.定義事件,連接ws
//發(fā)送ws
sendSocket() {
console.log('發(fā)送wx')
uni.sendSocketMessage({
data: JSON.stringify({
name: 'PC',
message: 'wx'
})
})
},
//連接ws
connect() {
if (this.connected || this.connecting) {
uni.showModal({
content: '正在連接或者已經(jīng)連接,請(qǐng)勿重復(fù)連接',
showCancel: false,
})
return
}
this.connecting = true
uni.showLoading({
title: '連接中...',
})
uni.connectSocket({
url: 'ws://localhost:8888',
success(res) {
// 這里是接口調(diào)用成功的回調(diào),不是連接成功的回調(diào),請(qǐng)注意
console.log('uni.connectSocket success', res)
},
fail(err) {
// 這里是接口調(diào)用失敗的回調(diào),不是連接失敗的回調(diào),請(qǐng)注意
console.log('uni.connectSocket fail', err)
},
})
//監(jiān)聽WebSocket連接打開事件
uni.onSocketOpen((res) => {
console.log('監(jiān)聽中')
if (this.pageVisible) {
this.connecting = false
this.connected = true
uni.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 = false
this.connected = false
uni.hideLoading()
uni.showModal({
content: '連接失敗,可能是websocket服務(wù)不可用,請(qǐng)稍后再試',
showCancel: false,
})
}
})
uni.onSocketMessage((res) => {
console.log('接收到了通知', res)
if (this.pageVisible) {
this.msg = res.data
console.log('onMessage', res)
}
})
uni.onSocketClose((res) => {
if (this.pageVisible) {
this.connected = false
this.msg = ''
console.log('onClose', res)
}
})
},
四、實(shí)現(xiàn)效果
文章來源地址http://www.zghlxwxcb.cn/news/detail-771260.html
到了這里,關(guān)于如何使用websocket+node.js實(shí)現(xiàn)pc后臺(tái)與小程序端實(shí)時(shí)通信的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!