web-socket-handler-imp.js 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. }
  9. register () {
  10. return ImApi.register({name: 'xu'}).then(res => {
  11. this.im_user_id = res.data.id
  12. return res
  13. })
  14. }
  15. /**
  16. * 创建WebSocket连接
  17. * 如:this.imWebSocket = new IMWebSocket();
  18. * this.imWebSocket.createSocket({url: 'ws://10.4.97.87:8001'});
  19. * 如果你使用本地服务器来测试,那么这里的url需要用ws,而不是wss,因为用wss无法成功连接到本地服务器
  20. * @param options 建立连接时需要的配置信息,这里是传入的url,即你的服务端地址,端口号不是必需的。
  21. */
  22. createConnection({options}) {
  23. this._socket = wx.connectSocket({
  24. url: options.url,
  25. header: {
  26. 'content-type': 'application/json'
  27. },
  28. method: 'GET'
  29. });
  30. this._onSocketOpen();
  31. this._onSocketMessage();
  32. this._onSocketError();
  33. this._onSocketClose();
  34. }
  35. _sendMsgImp({content, success, fail}) {
  36. this._socket.send({
  37. data: JSON.stringify(content),
  38. success: () => {
  39. success && success({content});
  40. },
  41. fail: (res) => {
  42. fail && fail(res);
  43. }
  44. });
  45. }
  46. /**
  47. * 关闭webSocket
  48. */
  49. closeConnection() {
  50. this._socket.close();
  51. }
  52. _onSocketError(cb) {
  53. this._socket.onError((res) => {
  54. this._isLogin = false;
  55. console.log('WebSocket连接打开失败,请检查!', res);
  56. })
  57. }
  58. _onSocketClose(cb) {
  59. this._socket.onClose((res) => {
  60. this._isLogin = false;
  61. console.log('WebSocket 已关闭!', res)
  62. });
  63. }
  64. _onSocketOpen() {
  65. ImApi.getContacts(getApp().globalData.userinfo.user_id)
  66. this._socket.onOpen((res) => {
  67. console.log('WebSocket连接已打开!');
  68. });
  69. }
  70. /**
  71. * webSocket是在这里接收消息的
  72. * 在socket连接成功时,服务器会主动给客户端推送一条消息类型为login的信息,携带了用户的基本信息,如id,头像和昵称。
  73. * 在login信息接收前发送的所有消息,都会被推到msgQueue队列中,在登录成功后会自动重新发送。
  74. * 这里我进行了事件的分发,接收到非login类型的消息,会回调监听函数。
  75. * @private
  76. */
  77. _onSocketMessage() {
  78. this._socket.onMessage((res) => {
  79. let msg = JSON.parse(res.data);
  80. if (msg.type === 'TYPE_ONE') {
  81. this._receiveListener && this._receiveListener(msg);
  82. }
  83. })
  84. }
  85. }