const io = require('../lib/Socket.io'); const {tutorial} = require('../utils/Bundle'); const {Api} = require('./Conf'); var Ws = function() { this.socket = new io(Api.SocketLocal, { autoConnect: false, //自动连接 reconnection: true, //断开自动重连 reconnectionDelay: 2000, //自动重连时间,默认为2000毫秒 reconnectionAttempts: 10, //最大重连尝试次数,默认为Infinity forceNew: true, // }) this.socket.on("connect", () => { console.log(`Socket connected: ${Api.SocketLocal}`); }) } Ws.prototype.open = function() { this.socket.open() } /** * 监听Websocket事件 * @param {String} eventName 监听事件名称 * @param {Function} callback 事件触发回调 */ Ws.prototype.on = function(eventName, callback) { if(eventName) { this.socket.on(eventName, data => { console.log(`Socket On Event: ${eventName}`); callback && callback(data) }) } } /** * 上报Websocket报文 * @param {String} eventName 上报事件名 * @param {Object} data 上报数据 */ Ws.prototype.emit = function(eventName, data) { if(eventName) { console.log(`Socket Do Emit: ${eventName}`, data); this.socket.emit(eventName, data); } } module.exports = new Ws();