实现思路和vue中是一样的。如果想看思路可以看这篇文章:websocket
直接上可以运行的代码:
一、后端nodeJS代码:
1、新建项目文件夹
2、初始化项目:
npm init -y
3、项目里安装ws
npm i ws --save
4、nodeJS代码:
chat.js
const WsServer = require("ws").Server;// 创建webscoket的服务器对象
const server = new WsServer({ port: 9000 });// 绑定connection事件(当有浏览器端连接时,会触发)let allClient = []; //保存着所有的客户端server.on("connection", (client) => {console.log("有人连接了");// 保存连接的客户端allClient.push(client);console.log("allClient.length", allClient.length);// 给所有客户端发送人数:sendCount();// 给当前客户端对象绑定message事件(当前该客户端给服务器发送消息时,触发client.on("message", (str) => {console.log("有人发了消息",str);// 把收到的消息转发给其它客户端sendMsg(client,str);});client.on("close", () => {sendMsg(client,"有人退出了");allClient = allClient.filter((item) => item != client);sendCount();});
});
// 发送消息
function sendMsg(client,content) {allClient.forEach((item) => {if (item != client) {item.send(JSON.stringify({status: "msg",content,}));}});
}// 发送人数
function sendCount() {allClient.forEach((item) => {item.send(JSON.stringify({status: "count",count: allClient.length,}));});
}
5、运行后端项目:
nodemon chat
二、前端uni-app代码
1、uni-app代码
<template><view><view>聊天:在线人数:{{count}}</view><view class="chat-box" v-html="allmsg"></view><input v-model="msg" /><button @click="sendMsg">发送</button><button @click="exitChat">退出聊天</button></view>
</template><script>export default {data() {return {allmsg: "",msg: "",count: 0}},onLoad() {const socketTask = uni.connectSocket({url: "ws://127.0.0.1:9000/",success() {}});console.log("socketTask", socketTask);uni.onSocketOpen(() => {console.log("服务器已经打开链接");// ws.send("大家好,我是新来的");uni.sendSocketMessage({data: "大家好,我是通过uni来的"})})uni.onSocketMessage((res) => {console.log('收到服务器内容:' + res.data);// this.allmsg += `<view>${res.data}</view>`;const obj = JSON.parse(res.data);if (obj.status == "msg") {console.log("typeof obj.content", typeof obj.content);console.log("obj.content", obj.content);this.allmsg += `<view>${this.blobToStr(obj.content.data)}</view>`;} else if (obj.status === "count") {console.log("obj.count", obj.count);this.count = obj.count;}})},methods: {exitChat(){uni.closeSocket();},blobToStr(data) {var enc = new TextDecoder("utf-8");var arr = new Uint8Array(data);return enc.decode(arr)},sendMsg() {uni.sendSocketMessage({data: this.msg})}}}
</script><style scoped>.chat-box {width: 100%;height: 800rpx;border: 1px solid red;}
</style>
2、运行项目,界面如下:
解释:当打开前端页面时,后端的socket会自动连接上