热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Uniapp如何全局使用websocket

此教程基于uniapp提供的uniapp-tools的socket.js插件1.创建socket.js(封装好的websocket连接对象)cons

此教程基于uniapp提供的uniapp-tools的socket.js插件

1.创建socket.js(封装好的websocket连接对象)

const noop = function() {};
class Socket {static stopTime &#61; 0;static concatCount &#61; 0;constructor({url &#61; &#39;&#39;,onOpen &#61; noop,onMsg &#61; noop,onClose &#61; noop,onError &#61; noop,onReload &#61; noop,onRdFinsh &#61; noop,maxInterValCount &#61; 10,interValTime &#61; 2000,SocketState &#61; {},...args} &#61; {}) {this.isRconnectIng &#61; false; //是否处于重连状态this.waiting &#61; Promise.resolve(false); //心跳检查必须等待重连完成后this.waitDep &#61; []; //等待时收集依赖的容器this.SocketTask &#61; {nsend: noop,nclose: noop,nrconnect: noop,isconnect: false,uniColse: false,maxInterValCount,interValTime,InterValCount: 0,eventPatch: null,url,onOpen,onMsg,onClose,onError,onReload,onRdFinsh,extra: args};this._EventDispath(this.SocketTask);this.initChat(this.SocketTask, this.SocketTask.extra);return this.SocketTask;}set CONCATCOUNT(value) {Socket.concatCount &#61; value;if (value > 0) this._notify();}get CONCATCOUNT() {return Socket.concatCount}/*** 仅供内部使用&#xff0c;通知所有收集到的依赖*/_notify() {for (let i &#61; 0; i < this.waitDep.length; i&#43;&#43;) {this.waitDep[i].call(this.SocketTask);}this.waitDep &#61; [];}/*** 仅供内部使用&#xff0c;确认当前是否连接成功,收集依赖*/_chunkConnect(fn) {if (Socket.concatCount > 0) {fn();} else {this.waitDep.push(fn);}}/*** 仅供内部使用&#xff0c;事件注册*/_EventDispath({onReload} &#61; {}) {let SocketTask &#61; this.SocketTask;let events &#61; {onOpen: [],onMsg: [],onClose: [],onError: [],onReload: [],onRdFinsh: [],}SocketTask.nsend &#61; text &#61;> {this._chunkConnect(() &#61;> {uni.sendSocketMessage({data: text})})}SocketTask.nclose &#61; t &#61;> {this._chunkConnect(() &#61;> {SocketTask.uniColse &#61; true;uni.closeSocket();})}SocketTask.nrconnect &#61; t &#61;> {this._chunkConnect(() &#61;> {this.waiting &#61; new Promise(async (resolve) &#61;> {uni.closeSocket();let reloadStatus &#61; false;try {const res &#61; await this.initChat(SocketTask, SocketTask.extra);reloadStatus &#61; res;} catch (e) {}onReload.call(SocketTask, reloadStatus, SocketTask);SocketTask.eventPatch.dispatchEvent(&#39;onReload&#39;, reloadStatus);resolve(reloadStatus);})})}function EventDispatcher() {this.events &#61; events;}for (let key in events) {EventDispatcher.prototype[key] &#61; function(handler) {if (typeof handler !&#61; &#39;function&#39;) return;this.events[key].push(handler)}}EventDispatcher.prototype.dispatchEvent &#61; function(type, msg) {let evenArr &#61; this.events[type];if (evenArr.length > 0) {for (let i &#61; 0; i < evenArr.length; i&#43;&#43;) {evenArr[i].call(SocketTask, msg, SocketTask);}}}SocketTask.eventPatch &#61; new EventDispatcher();}/*** 心跳检测*/async hbDetection() {const SocketTask &#61; this.SocketTask;if (SocketTask.uniColse) {return false;}clearTimeout(Socket.stopTime);if (!SocketTask.isconnect) { //未连接则启动连接if (SocketTask.maxInterValCount > SocketTask.InterValCount) {Socket.stopTime &#61; setTimeout(async () &#61;> {try {const R_result &#61; await this.waiting;if (R_result) return;this.isRconnectIng &#61; true;const openResult &#61; await this.initChat(SocketTask, SocketTask.extra);if (openResult) return;SocketTask.InterValCount&#43;&#43;;return this.hbDetection();} catch (e) {return this.hbDetection();}}, SocketTask.interValTime)} else {SocketTask.onRdFinsh.call(SocketTask, SocketTask.maxInterValCount, SocketTask);SocketTask.eventPatch.dispatchEvent(&#39;onRdFinsh&#39;, SocketTask.maxInterValCount);}}}/*** websocket监听事件*/SocketEvents({onOpen,onMsg,onClose,onError,onReload,} &#61; {}) {return new Promise((resolve, reject) &#61;> {const SocketTask &#61; this.SocketTask;uni.onSocketOpen(res &#61;> {this.CONCATCOUNT &#43;&#61; 1;this.isRconnectIng &#61; false;SocketTask.isconnect &#61; true;SocketTask.InterValCount &#61; 0;SocketTask.uniColse &#61; false;resolve(true);onOpen.call(SocketTask, res, SocketTask);SocketTask.eventPatch.dispatchEvent(&#39;onOpen&#39;, res)})uni.onSocketMessage(msg &#61;> {onMsg.call(SocketTask, msg, SocketTask);SocketTask.eventPatch.dispatchEvent(&#39;onMsg&#39;, msg)})uni.onSocketClose(async err &#61;> {SocketTask.isconnect &#61; false;resolve(false);if (!this.isRconnectIng) {this.hbDetection();onClose.call(SocketTask, err, SocketTask);SocketTask.eventPatch.dispatchEvent(&#39;onClose&#39;, err);}})uni.onSocketError(err &#61;> {uni.closeSocket();onError.call(SocketTask, err, SocketTask);SocketTask.eventPatch.dispatchEvent(&#39;onError&#39;, err)})})}/*** 开始初始化chat*/initChat({url,onOpen,onMsg,onClose,onError,onReload} &#61; {}, args) {return new Promise(async (resolve, reject) &#61;> {try {await this.connectSocket(url, args);let res &#61; await this.SocketEvents({onOpen,onMsg,onClose,onError,onReload,})resolve(res);} catch (e) {console.log(e)reject();}})}/*** 连接webSocket*/connectSocket(url, args) {return new Promise((resolve, reject) &#61;> {uni.connectSocket({url,success: () &#61;> {resolve();},fail: err &#61;> {reject();},...args})})}
}
export default Socket

2.创建useWebSocket.js

import Vue from &#39;vue&#39;
import store from "./index.js"; //引入vuex&#xff0c;引入自己的路径
import socket from "../store/socket.js"; //引入socket.js&#xff0c;引入自己的路径
//这里将socket.js中的创建连接和接受消息的监听放到一个可以向外部暴露的方法&#xff0c;方便在合适的时机创建websocket连接
export function connectWebSocket(){const Socket &#61;new socket({url: &#39;ws://127.0.0.1:8086/ws&#39;, //连接地址 必填onOpen(res) {console.log(&#39;连接成功&#39;)},onClose(err) {console.log(&#39;关闭了连接&#39;)},onReload(res) {console.log(&#39;重载&#xff1a;&#39; &#43; res)},onMsg(msg) {console.log(msg)}});//加入监听&#xff0c;就可以全局使用监听了Socket.eventPatch.onOpen((msg,sk)&#61;>{ //监听是否连接成功});Socket.eventPatch.onMsg((msg,sk)&#61;>{ //监听是否接受消息console.log(msg)});Vue.prototype.$Socket &#61; Socket; //连接成功挂在到原型上
}

3.修改 main.js

import Vue from &#39;vue&#39;
import App from &#39;./App&#39;import store from &#39;&#64;/store&#39; //引入自己的路径
import &#39;./store/useSocket.js&#39; //引入自己的路径Vue.prototype.$store&#61;store
Vue.config.productionTip &#61; falseApp.mpType &#61; &#39;app&#39;const app &#61; new Vue({...App
})
app.$mount()

4.修改vuex的js文件index.js

import Vue from &#39;vue&#39;
import Vuex from &#39;vuex&#39;
Vue.use(Vuex)
const store &#61;new Vuex.Store({state: {SocketState: {},SocketStateErr: {},},mutations:{setSocketState(that, info) {that.SocketState &#61; info},setSocketStateErr(that, info) {that.SocketStateErr &#61; info;}},
})
export default store

5.案例


1&#xff09;Login.vue登录页面,主要看登录的实现


2)message.vue



推荐阅读
author-avatar
用户t59kdjdcr6
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有