当前位置: 首页 > news >正文

uni-app里使用webscoket

实现思路和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会自动连接上

 

 

http://www.lryc.cn/news/144443.html

相关文章:

  • jdk17+springboot使用webservice,踩坑记录
  • 计算机网络文件拆分—视频流加载、断点续传
  • JVM 给对象分配内存空间
  • Excel·VBA二维数组组合函数、组合求和
  • 调用自实现MyGetProcAddress获得CreateFileA函数并调用创建写入文件
  • Leetcode 191.位1的个数
  • 安防监控视频平台EasyCVR视频汇聚平台调用接口出现跨域现象的问题解决方案
  • Python中的一些常用操作
  • go语言调用python脚本
  • 2.3 【MySQL】命令行和配置文件中启动选项的区别
  • 外部库/lib/maven依赖项 三者关系
  • 在线制作作息时间表
  • 他们朝我扔泥巴(scratch)
  • docker部署前端项目保姆级教程
  • 《C和指针》笔记13: static关键字总结
  • Docker harbor私有仓库部署与管理
  • 解锁Selenium的力量:不仅仅是Web测试
  • [SQLITE_ERROR] SQL error or missing database (near “=“: syntax error)【已解决】
  • 【视觉系统】笔芯内径机器视觉测量软硬件方案-康耐德智能
  • 将文件夹的名称写到Excel中
  • 关于Vue CLI项目 运行发生了 less-lorder错误的解决方案
  • 【Qt学习】02:信号和槽机制
  • 软件工程(十三) 设计模式之结构型设计模式(一)
  • Node与Express后端架构:高性能的Web应用服务
  • C++炸弹小游戏
  • 发送通知消息
  • Python报错:PermissionError: [Errno 13] Permission denied解决方案
  • 【leetcode】第六章 二叉树part01
  • All In One!Meta发布SeamlessM4T,支持100种语言,35种语音、开源、在线体验!
  • Python可视化工具库实战