websocket.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. import config from '../config'
  2. import storage from './storage'
  3. import {navigateTo} from './utils'
  4. export default {
  5. connected: false,
  6. connecting: false,
  7. socketTask: false,
  8. timer: 3000,
  9. link:0,
  10. /**
  11. * 创建 WebSocket 连接。
  12. */
  13. connect(kf_id){
  14. let users = storage.getJson("users");
  15. if(users == null){
  16. navigateTo("public/login");
  17. return false;
  18. }
  19. if(this.isConnect()){
  20. return false;
  21. }
  22. this.connecting = true;
  23. this.socketTask = uni.connectSocket({
  24. url: config.web_socket_url,
  25. header: {
  26. 'content-type': 'application/json'
  27. },
  28. complete: ()=> {}
  29. });
  30. // 监听WebSocket连接打开事件。
  31. this.socketTask.onOpen((res) => {
  32. this.connecting = false
  33. this.connected = true
  34. this.send({type:"login", auth:users.token,service_id:kf_id});
  35. });
  36. this.error();
  37. this.close();
  38. },
  39. /**
  40. * 检查是否己连接
  41. */
  42. isConnect(){
  43. if (this.connected || this.connecting) {
  44. return true;
  45. }
  46. return false;
  47. },
  48. /**
  49. * 重新连接websocket
  50. */
  51. reConnect(){
  52. this.close();
  53. this.connect();
  54. },
  55. /**
  56. * 监听 WebSocket 接受到服务器的消息事件
  57. * @param {Object} callback
  58. */
  59. message(callback){
  60. if(this.socketTask != null && this.socketTask.onMessage){
  61. this.socketTask.onMessage(callback);
  62. }
  63. },
  64. send(data){
  65. if(typeof data == "object"){
  66. data = JSON.stringify(data);
  67. }
  68. let that = this;
  69. return new Promise((resolve, reject)=>{
  70. that.socketTask.send({
  71. data:data,
  72. success(res){
  73. resolve(res);
  74. },
  75. fail(err){
  76. reject(err);
  77. }
  78. })
  79. });
  80. },
  81. error(){
  82. this.socketTask.onError((err) => {
  83. this.connecting = false
  84. this.connected = false
  85. // uni.hideLoading()
  86. // uni.showModal({
  87. // content: '与服务器断开连接,请稍后再试',
  88. // showCancel: false
  89. // });
  90. });
  91. },
  92. close(){
  93. if(this.link > 2) {
  94. return ;
  95. }
  96. if (this.socketTask && this.socketTask.close) {
  97. this.socketTask.onClose((res) => {
  98. this.connected = false;
  99. this.socketTask = false;
  100. this.link+=1;
  101. setTimeout(()=>{
  102. //this.connect();
  103. },this.timer);
  104. })
  105. }
  106. }
  107. }