socket.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. class wsRequest {
  2. constructor(url, time) {
  3. this.status = null; // websocket是否关闭
  4. this.lockReconnect = false //避免重复连接
  5. this.url = url
  6. //心跳检测
  7. this.timeout= time //多少秒执行检测
  8. this.timeoutObj= null //检测服务器端是否还活着
  9. this.reconnectTimeOutObj= null //重连之后多久再次重连
  10. try {
  11. return this.initRequest()
  12. } catch (e) {
  13. console.log('catch');
  14. this.reconnect();
  15. }
  16. }
  17. initRequest() {
  18. this.socketTask = uni.connectSocket({
  19. url: this.url, //接口地址。
  20. success: () => {
  21. console.log('连接成功');
  22. // 返回实例
  23. return this.socketTask
  24. }
  25. })
  26. this.socketTask.onOpen(res => {
  27. console.log(res, '连接打开');
  28. // 清除重连定时器
  29. clearTimeout(this.reconnectTimeOutObj)
  30. // 开启检测
  31. this.start()
  32. })
  33. // 如果希望websocket连接一直保持,在close或者error上绑定重新连接方法。
  34. this.socketTask.onClose((res) => {
  35. console.log(res, '连接关闭');
  36. this.reconnect();
  37. })
  38. this.socketTask.onError((res) => {
  39. console.log(res, '连接错误');
  40. this.reconnect();
  41. })
  42. this.socketTask.onMessage(res => {
  43. //接受任何消息都说明当前连接是正常的
  44. this.reset();
  45. console.log(res, 'pong');
  46. })
  47. }
  48. send(value) {
  49. return new Promise((resovle,reject)=>{
  50. this.socketTask.send({
  51. data: value,
  52. success:()=>{
  53. resovle('发送成功')
  54. }
  55. })
  56. })
  57. }
  58. // reset和start方法主要用来控制心跳的定时。
  59. reset(){
  60. // 清除定时器重新发送一个心跳信息
  61. clearTimeout(this.timeoutObj);
  62.      this.start();
  63. }
  64. start(){
  65. this.timeoutObj = setTimeout(() => {
  66. //这里发送一个心跳,后端收到后,返回一个心跳消息,
  67. //onmessage拿到返回的心跳就说明连接正常
  68. console.log('ping');
  69. this.socketTask.send({data:"ping"});
  70. }, this.timeout)
  71. }
  72. // 重连
  73. reconnect() {
  74. // 防止多个方法调用,多处重连
  75. if (this.lockReconnect) {
  76. return;
  77. };
  78. this.lockReconnect = true;
  79. console.log('准备重连');
  80. //没连接上会一直重连,设置延迟避免请求过多
  81. this.reconnectTimeOutObj = setTimeout(()=>{
  82. // 重新连接
  83. this.initRequest()
  84. this.lockReconnect = false;
  85. }, 4000);
  86. }
  87. // 手动关闭
  88. close() {
  89. this.socketTask.close()
  90. }
  91. }
  92. module.exports = wsRequest