【Uniapp封装的websocket,无脑复制,粘贴即可使用】

首先先封装一份websocket.js文件

class websocket{
	constructor(url, time) {
		this.is_open_socket = false //避免重复连接
		this.url = url //地址
		this.data = null
		//心跳检测
		this.timeout = time //多少秒执行检测
		this.heartbeatInterval = null //检测服务器端是否还活着
		this.reconnectTimeOut = null //重连之后多久再次重连
		try {
			return this.connectSocketInit()
		} catch (e) {
			 
			this.is_open_socket = false
			this.reconnect();
		}
	}
 
	// 进入这个页面的时候创建websocket连接【整个页面随时使用】
	connectSocketInit() {
		if(uni.getStorageSync('userinfo')==null){
			   var uid=0
		}else{
			  var uid= uni.getStorageSync('userinfo').id
		}
		this.socketTask = uni.connectSocket({
			url: this.url,
			header: {
					'token':uid
			},
			success: () => {
				console.log("正准备建立websocket中...");
				// 返回实例
				return this.socketTask
			},
		});
		this.socketTask.onOpen((res) => {
			console.log("WebSocket连接正常!");
			clearTimeout(this.reconnectTimeOut)
			clearTimeout(this.heartbeatInterval)
			this.is_open_socket = true;
			this.start();
			// // 注:只有连接正常打开中 ,才能正常收到消息
			//这里处理后端主动推送的消息
			this.socketTask.onMessage((res) => {
					var res=JSON.parse(res.data)
					switch(res.type){
						  case -1://创建聊天室
						      //uiapp自带的跨页面存储信息,也可以使用vuex 缓存聊天信息,在维护vuex聊天信息
						       uni.$emit('getAddChat',res.data)
						      break;
						  case 1:// 更新消息列表
						   uni.$emit('getMsgList',res.data)
						  break;
					      case 2://聊天室最新数据列表
						  uni.$emit('getChatList',res.data)
						   break;
						  case 3://发送消息
						   uni.$emit('getChatSend',res.data)
						  break;
					}
			});
		})
		// 这里仅是事件监听【如果socket关闭了会执行】
		this.socketTask.onClose(() => {
			console.log("已经被关闭了")
			this.is_open_socket = false;
			this.reconnect();
		})
	}
 
	//发送消息
	async send(value) {			 
	  await new Promise((resolve) => {
	    setTimeout(() => {
	      resolve();
	    }, 1000);
	  });
	  // 注:只有连接正常打开中,才能正常成功发送消息
	  this.socketTask.send({
	    data: value,
	    async success() {
	      console.log("消息发送成功",value);
	    },
	  });
	}

	//开启心跳检测
	start() {
		this.heartbeatInterval = setInterval(() => {
			this.data = "心跳"
			this.send(this.data);
		}, this.timeout)
	}
	//重新连接
	reconnect() {
		//停止发送心跳
		clearInterval(this.heartbeatInterval)
		//如果不是人为关闭的话,进行重连
		if (!this.is_open_socket) {
			this.reconnectTimeOut = setTimeout(() => {
				this.connectSocketInit();
			}, 3000)
		}
	}
	//外部获取消息
	getMessage(callback) {
		this.socketTask.onMessage((res) => {
			return callback(res)
		})
	}
 
}
 
module.exports = websocket

引用全局js main.js

//注意引用路径,文件位置随便放
import wsRequest from "@/util/websocke.js"
// // 开启websocket
// let websocket = new wsRequest("wss://域名/wss",5000) //正式环境
let websocket = new wsRequest("ws://127.0.0.1:2346",5000) //本地环境
// //挂载到全局
Vue.prototype.$ws = websocket

聊天室使用

<script>
	export default {

		data() {
			return {
				msgList: [],
			}
		},
		onUnload() {
			// 移除监听事件(注意页面卸载时移除全局使用)
			uni.$off('getMsgList');
		},
		onLoad() {
			this.monitorList()
		},
		onShow(){
			this.getIMList()
		},
		methods: {
			//请求消息列表
			getIMList() {
				let that = this;
				let user_id = ‘用户标识’
				let data = {
					"user_id": user_id,
					"method": "list"
				} 
				//请求消息列表
				that.$ws.send(JSON.stringify(data));
			},
			//实时获取消息列表
			monitorList() {
				uni.showLoading()
				var that = this;
				//此处与uni.$emit 一同使用
				uni.$on('getMsgList', data => {
					that.msgList = data
					uni.hideLoading()
				})
			},
		}
	}
</script>

后端PHP使用tp框架及workerman搭建服务端websocket服务直达链接

后端PHP使用tp框架及workerman搭建服务端websocket服务直达链接

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
要在uniapp封装WebSocket并全局使用,可以按照以下步骤操作: 1. 创建一个WebSocket.js文件,用于封装WebSocket的相关逻辑。在该文件,可以定义WebSocket的连接、发送和关闭等方法。 ``` export default { socketTask: null, // 连接websocket connect(url) { this.socketTask = uni.connectSocket({ url: url, success: () => { console.log('WebSocket连接成功') } }) this.socketTask.onOpen(() => { console.log('WebSocket连接打开') }) this.socketTask.onMessage((res) => { console.log('WebSocket收到消息', res) }) this.socketTask.onError((res) => { console.log('WebSocket连接错误', res) }) this.socketTask.onClose((res) => { console.log('WebSocket连接关闭', res) }) }, // 发送消息 send(msg) { this.socketTask.send({ data: msg, success: () => { console.log('WebSocket发送消息成功', msg) } }) }, // 关闭连接 close() { this.socketTask.close({ success: () => { console.log('WebSocket连接关闭成功') } }) } } ``` 2. 在main.js引入WebSocket.js,并将其挂载到Vue原型上,以便在全局使用。 ``` import Vue from 'vue' import App from './App' import WebSocket from './WebSocket' Vue.prototype.$socket = WebSocket Vue.config.productionTip = false App.mpType = 'app' const app = new Vue({ ...App }) app.$mount() ``` 3. 在需要使用WebSocket的页面或组件,可以通过this.$socket来调用WebSocket的连接、发送和关闭等方法。 ``` export default { created() { this.$socket.connect('ws://localhost:8080') this.$socket.send('Hello, WebSocket!') }, beforeDestroy() { this.$socket.close() } } ``` 这样,我们就可以在uniapp封装WebSocket并全局使用了。需要注意的是,WebSocket的连接地址应该根据实际情况进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是誰萆微了承諾

你的鼓励是对我最大的支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值