给公司在百度上做网站,巨好用网络企业管理系统,抖音代运营投诉平台,河南如何建网站要什么条件实现思路和vue中是一样的。如果想看思路可以看这篇文章#xff1a;websocket
直接上可以运行的代码#xff1a;
一、后端nodeJS代码#xff1a;
1、新建项目文件夹
2、初始化项目#xff1a;
npm init -y
3、项目里安装ws
npm i ws --save
4、nodeJS代码#xff1…实现思路和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代码
templateviewview聊天在线人数{{count}}/viewview classchat-box v-htmlallmsg/viewinput v-modelmsg /button clicksendMsg发送/buttonbutton clickexitChat退出聊天/button/view
/templatescriptexport 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})}}}
/scriptstyle scoped.chat-box {width: 100%;height: 800rpx;border: 1px solid red;}
/style2、运行项目界面如下
解释当打开前端页面时后端的socket会自动连接上