uniapp websocket的封装与使用

一、新建websocket.js文件

在common目录下新建一个websocket.js文件,完整代码如下

class websocketUtil {
	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) {
			console.log('catch');
			this.is_open_socket = false
			this.reconnect();
		}
	}

	// 进入这个页面的时候创建websocket连接【整个页面随时使用】
	connectSocketInit() {
		this.socketTask = uni.connectSocket({
			url: this.url,
			success: () => {
				console.log("正准备建立websocket中...");
				// 返回实例
				return this.socketTask
			},
		});
		this.socketTask.onOpen((res) => {
			console.log("WebSocket连接正常!");
			clearTimeout(this.reconnectTimeOut)
			clearTimeout(t
UniApp 是一个跨平台的应用开发框架,可以使用 Vue.js 开发多个平台的应用。在 UniApp使用 WebSocket 需要进行封装和调用。 1. 首先,在 `common` 目录下创建一个 `utils` 文件夹,并在该文件夹下创建一个 `websocket.js` 文件。 2. 在 `websocket.js` 中编写 WebSocket封装代码,如下所示: ```javascript // 导出一个函数,用于创建 WebSocket 连接 export function createWebSocket(url, onMessage, onError, onClose) { // 创建 WebSocket 对象 const socket = new WebSocket(url); // 监听 WebSocket 的打开事件 socket.onopen = function () { console.log('WebSocket 连接已打开'); }; // 监听 WebSocket 的消息事件 socket.onmessage = function (event) { onMessage(event.data); }; // 监听 WebSocket 的错误事件 socket.onerror = function (error) { onError(error); }; // 监听 WebSocket 的关闭事件 socket.onclose = function () { onClose(); }; // 返回 WebSocket 对象,方便其他地方使用 return socket; } ``` 3. 在需要使用 WebSocket 的页面中,引入 `websocket.js` 并调用 `createWebSocket` 函数创建 WebSocket 连接,如下所示: ```javascript import { createWebSocket } from '@/common/utils/websocket.js'; export default { mounted() { // 创建 WebSocket 连接 this.socket = createWebSocket( 'ws://localhost:8080', // WebSocket 服务器地址 this.handleMessage, // 接收消息时的回调函数 this.handleError, // 发生错误时的回调函数 this.handleClose // 连接关闭时的回调函数 ); }, methods: { // 处理接收到的消息 handleMessage(data) { console
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值