web-socket-handler-imp.js 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. import IIMHandler from "../interface/i-im-handler";
  2. import ImApi from './../../../apis/im'
  3. export default class WebSocketHandlerImp extends IIMHandler {
  4. constructor() {
  5. super();
  6. this._socket = null
  7. this.im_user_id = null
  8. this.options = null
  9. this.timer = null
  10. }
  11. register () {
  12. return ImApi.register({name: 'xu'}).then(res => {
  13. this.im_user_id = res.data.id
  14. return res
  15. })
  16. }
  17. /**
  18. * 创建WebSocket连接
  19. * 如:this.imWebSocket = new IMWebSocket();
  20. * this.imWebSocket.createSocket({url: 'ws://10.4.97.87:8001'});
  21. * 如果你使用本地服务器来测试,那么这里的url需要用ws,而不是wss,因为用wss无法成功连接到本地服务器
  22. * @param options 建立连接时需要的配置信息,这里是传入的url,即你的服务端地址,端口号不是必需的。
  23. */
  24. createConnection({options = this.options}) {
  25. this._socket = wx.connectSocket({
  26. url: options.url,
  27. header: {
  28. 'content-type': 'application/json'
  29. },
  30. method: 'GET',
  31. success: () => {
  32. console.log('成功连接')
  33. },
  34. fail: () => {
  35. console.log('连接失败')
  36. }
  37. });
  38. this.intervalSendMsg()
  39. this.options = options
  40. console.log(this.options, 'options')
  41. this._onSocketOpen();
  42. this._onSocketMessage();
  43. this._onSocketError();
  44. this._onSocketClose();
  45. }
  46. reconnect () {
  47. console.log(this.options, 'this.option')
  48. this._socket = wx.connectSocket({
  49. url: this.options.url,
  50. header: {
  51. 'content-type': 'application/json'
  52. },
  53. method: 'GET'
  54. });
  55. this._onSocketOpen();
  56. this._onSocketMessage();
  57. this._onSocketError();
  58. this._onSocketClose();
  59. console.log('重新连接')
  60. }
  61. _sendMsgImp({content, success, fail}) {
  62. console.log(content, 'content')
  63. this._socket.send({
  64. data: JSON.stringify(content),
  65. success: () => {
  66. success && success({content});
  67. },
  68. fail: (res) => {
  69. console.log(res, 'error')
  70. if (res.errMsg === 'SocketTask.send:fail SocketTask.readyState is not OPEN') {
  71. // 发送消息失败,重新连接socket
  72. this.closeConnection()
  73. this.createConnection({options: this.options})
  74. }
  75. fail && fail(res);
  76. }
  77. });
  78. }
  79. /**
  80. * 关闭webSocket
  81. */
  82. closeConnection() {
  83. console.log('关闭socket')
  84. this._socket && this._socket.close();
  85. }
  86. _onSocketError(cb) {
  87. this._socket.onError((res) => {
  88. // this._isLogin = false;
  89. this._socket = null
  90. console.log('WebSocket连接打开失败,请检查!', res);
  91. })
  92. }
  93. _onSocketClose(cb) {
  94. this._socket.onClose((res) => {
  95. // 1分钟无消息后端自动断开连接,code 1006 需要重连socket
  96. if (res.code === 1006) {
  97. this._socket = wx.connectSocket({
  98. url: this.options.url,
  99. success: (res) => {
  100. console.log('重连成功', res)
  101. },
  102. fail: (err) => {
  103. console.log('重连失败', err)
  104. }
  105. });
  106. return
  107. }
  108. clearInterval(this.timer)
  109. this.timer = null
  110. console.log('WebSocket 已关闭!', res)
  111. });
  112. }
  113. _onSocketOpen() {
  114. ImApi.getContacts(getApp().globalData.userinfo.user_id)
  115. this._socket.onOpen((res) => {
  116. console.log('WebSocket连接已打开!');
  117. });
  118. }
  119. /**
  120. * webSocket是在这里接收消息的
  121. * 在socket连接成功时,服务器会主动给客户端推送一条消息类型为login的信息,携带了用户的基本信息,如id,头像和昵称。
  122. * 在login信息接收前发送的所有消息,都会被推到msgQueue队列中,在登录成功后会自动重新发送。
  123. * 这里我进行了事件的分发,接收到非login类型的消息,会回调监听函数。
  124. * @private
  125. */
  126. _onSocketMessage() {
  127. this._socket.onMessage((res) => {
  128. console.log(res, 'receive msg')
  129. let msg = JSON.parse(res.data);
  130. if (msg.type === 'TYPE_ONE') {
  131. this._receiveListener.forEach(fn => {
  132. fn(msg)
  133. })
  134. // this._receiveListener && this._receiveListener(msg);
  135. }
  136. })
  137. }
  138. intervalSendMsg () {
  139. this.timer = setInterval(() => {
  140. // 定时发消息,免得后端自动断开
  141. this._socket.send({data: JSON.stringify({content: '定时发消息'})})
  142. }, 50000);
  143. }
  144. }