如何使用websocket+node.js实现pc后台与小程序端实时通信

如何使用websocket+node.js实现pc后台与小程序端实时通信

实现功能:实现pc后台与小程序端互发通信能够实时检测到

一、使用node.js创建一个服务器

  • 1.安装ws依赖
bash 复制代码
npm i ws
  • 2.创建index.js
javascript 复制代码
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关闭的时候,要清空对应的ws
      if (wsList[item].readyState !== 1) {
        delete wsList[item]
      }
    })
  })
})
  • 3.打开终端,启动服务
bash 复制代码
node index.js

二、pc后台连接ws

html 复制代码
<!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后台</span>
    </div>
    <input type="text" id="input" />
    <button id="button">发送</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')
      //发送事件
      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.创建两个按钮,连接按钮,发送按钮
html 复制代码
<view @click="connect()">连接</view>
<view @click="sendSocket()">发送</view>
  • 2.定义事件,连接ws
javascript 复制代码
//发送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 = true
	uni.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 = 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服务不可用,请稍后再试',
				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)
		}
	})
},

四、实现效果

相关推荐
guanpinkeji2 小时前
卡牌抽卡机小程序:市场发展下的创新
小程序·团队开发·小程序开发·抽卡机·抽卡机小程序·卡牌·卡牌小程序
I592O9297832 小时前
二二复制模式小程序商城开发
小程序
林太白2 小时前
❤Node09-用户信息token认证
数据库·后端·mysql·node.js
JOJO___5 小时前
Node.js Express中使用joi进行表单验证
node.js·express
工业互联网专业5 小时前
毕业设计选题:基于ssm+vue+uniapp的捷邻小程序
vue.js·小程序·uni-app·毕业设计·ssm·源码·课程设计
战神刘玉栋8 小时前
《微信小程序实战(2) · 组件封装》
微信小程序·小程序·notepad++
傻虎贼头贼脑8 小时前
day21JS-npm中的部分插件使用方法
前端·npm·node.js
前端没钱10 小时前
若依Nodejs后台、实现90%以上接口,附体验地址、源码、拓展特色功能
前端·javascript·vue.js·node.js
dgiij10 小时前
AutoX.js向后端传输二进制数据
android·javascript·websocket·node.js·自动化
CaptainDrake10 小时前
包管理工具
npm·node.js