1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
| import { io } from "socket.io-client"; import Methods from "./methods.js"; import store from "@/store"; import * as types from "@/store/types";
export const linkSocket = ({ url, options, eventName, callback = () => {} }) => { let obj = { url: url, socket: null, success: false };
let timer = null;
store.state.socketArray.forEach((item) => { if (url === item.url) { obj = item; if (item.success) { if (timer) clearTimeout(timer); callback({ code: 1, data: "已连接" }); } else { setTimeout(() => { linkSocket({ url, options, eventName, callback }); }, 1000); } } });
if (obj.socket && !obj.success) return;
if (!obj.socket) { obj.socket = io(url, options); store.commit(types.SET_SOCKETARRAY, [...store.state.socketArray, obj]); } obj.socket.on("connect", (data) => { if (timer) clearTimeout(timer); obj.success = true; callback({ code: 1, data: "连接成功" }); console.log(obj.socket); socketOn(eventName, obj.socket); });
obj.socket.on("disconnect", (reason) => { obj.success = false; if (reason === "transport close") console.log("断开链接:连接被关闭(例如:用户失去连接,或者网络由WiFi切换到4G)"); else if (reason === "io server disconnect") console.log("断开链接:服务器使用socket.disconnect()强制断开了套接字。"); else if (reason === "io client disconnect") console.log("断开链接:使用socket.disconnect()手动断开socket。"); else if (reason === "ping timeout") console.log("断开链接:服务器没有在pingInterval + pingTimeout范围内发送PING"); else if (reason === "transport error") console.log("断开链接:连接遇到错误(例如:服务器在HTTP长轮询周期期间被杀死)"); else console.log("断开链接:", reason); });
obj.socket.on("connect_error", (data) => { console.log(`连接错误,重连中:${data}`); });
timer = setTimeout(() => { if (!obj.success) { obj.socket.close(); const socketArray = store.state.socketArray.filter((item) => { return item.url !== obj.url; }); store.commit(types.SET_SOCKETARRAY, socketArray); callback({ code: 0, data: "连接超时,检查服务" }); } }, 5000); };
export const socketOn = async (eventName, socket) => { if (socket._callbacks[`$${eventName}`]) return; socket.on(eventName, async (data, callback) => { if (Methods[eventName]) Methods[eventName](data, callback); }); };
export const socketEmit = async (eventName, data) => { return new Promise(async (resolve) => { const res = await getSocket(data); if (res.code === 0) { resolve(res); } else { res.socket.emit(eventName, data); resolve({ code: 1, data: "发送成功" }); } }); };
export const getSocket = (data) => { let obj = { url: data.url, socket: null, success: false };
store.state.socketArray.forEach((item) => { if (data.url === item.url) obj = item; }); if (!obj.socket) return { code: 0, data: "没查到socket连接" }; if (!obj.success) return { code: 0, data: "socket未正常连接" }; return { code: 1, socket: obj.socket }; };
|