此教程基于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}_notify() {for (let i &#61; 0; i < this.waitDep.length; i&#43;&#43;) {this.waitDep[i].call(this.SocketTask);}this.waitDep &#61; [];}_chunkConnect(fn) {if (Socket.concatCount > 0) {fn();} else {this.waitDep.push(fn);}}_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);}}}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)})})}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();}})}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";
import socket from "../store/socket.js";
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)}});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
收到的消息内容
请输入朋友ID
输入发送内容