1
0

Ws.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. const io = require('../lib/Socket.io');
  2. const {tutorial} = require('../utils/Bundle');
  3. const {Api} = require('./Conf');
  4. var Ws = function() {
  5. this.socket = new io(Api.SocketLocal, {
  6. autoConnect: false, //自动连接
  7. reconnection: true, //断开自动重连
  8. reconnectionDelay: 2000, //自动重连时间,默认为2000毫秒
  9. reconnectionAttempts: 10, //最大重连尝试次数,默认为Infinity
  10. forceNew: true, //
  11. })
  12. this.socket.on("connect", () => {
  13. console.log(`Socket connected: ${Api.SocketLocal}`);
  14. })
  15. }
  16. Ws.prototype.open = function() {
  17. this.socket.open()
  18. }
  19. /**
  20. * 监听Websocket事件
  21. * @param {String} eventName 监听事件名称
  22. * @param {Function} callback 事件触发回调
  23. */
  24. Ws.prototype.on = function(eventName, callback) {
  25. if(eventName) {
  26. this.socket.on(eventName, data => {
  27. console.log(`Socket On Event: ${eventName}`);
  28. callback && callback(data)
  29. })
  30. }
  31. }
  32. /**
  33. * 上报Websocket报文
  34. * @param {String} eventName 上报事件名
  35. * @param {Object} data 上报数据
  36. */
  37. Ws.prototype.emit = function(eventName, data) {
  38. if(eventName) {
  39. console.log(`Socket Do Emit: ${eventName}`, data);
  40. this.socket.emit(eventName, data);
  41. }
  42. }
  43. module.exports = new Ws();