websocket.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. class websocketUtil {
  2. constructor(url, time) {
  3. this.is_open_socket = false //避免重复连接
  4. this.url = url //地址
  5. this.data = null
  6. //心跳检测
  7. this.timeout= time //多少秒执行检测
  8. this.heartbeatInterval= null //检测服务器端是否还活着
  9. this.reconnectTimeOut= null //重连之后多久再次重连
  10. try {
  11. return this.connectSocketInit()
  12. } catch (e) {
  13. console.log('catch');
  14. this.is_open_socket = false
  15. this.reconnect();
  16. }
  17. }
  18. // 进入这个页面的时候创建websocket连接【整个页面随时使用】
  19. connectSocketInit() {
  20. this.socketTask = uni.connectSocket({
  21. url: this.url,
  22. success:()=>{
  23. console.log("正准备建立websocket中...");
  24. // 返回实例
  25. return this.socketTask
  26. },
  27. });
  28. this.socketTask.onOpen((res) => {
  29. console.log("WebSocket连接正常!");
  30. clearTimeout(this.reconnectTimeOut)
  31. clearTimeout(this.heartbeatInterval)
  32. this.is_open_socket = true;
  33. this.start();
  34. // 注:只有连接正常打开中 ,才能正常收到消息
  35. // this.socketTask.onMessage((res) => {
  36. // let data = JSON.parse(res.data)
  37. // console.log(data);
  38. // });
  39. })
  40. // 监听连接失败,这里代码我注释掉的原因是因为如果服务器关闭后,和下面的onclose方法一起发起重连操作,这样会导致重复连接
  41. // uni.onSocketError((res) => {
  42. // console.log('WebSocket连接打开失败,请检查!');
  43. // this.is_open_socket = false;
  44. // this.reconnect();
  45. // });
  46. // 这里仅是事件监听【如果socket关闭了会执行】
  47. this.socketTask.onClose(() => {
  48. console.log("已经被关闭了")
  49. this.is_open_socket = false;
  50. this.reconnect();
  51. })
  52. }
  53. //发送消息
  54. send(value){
  55. // 注:只有连接正常打开中 ,才能正常成功发送消息
  56. this.socketTask.send({
  57. data: value,
  58. async success() {
  59. console.log("消息发送成功");
  60. },
  61. });
  62. }
  63. //开启心跳检测
  64. start(){
  65. this.heartbeatInterval = setTimeout(()=>{
  66. this.data={value:"传输内容",method:"方法名称"}
  67. this.send(JSON.stringify(this.data));
  68. },this.timeout)
  69. }
  70. //重新连接
  71. reconnect(){
  72. //停止发送心跳
  73. clearInterval(this.heartbeatInterval)
  74. //如果不是人为关闭的话,进行重连
  75. if(!this.is_open_socket){
  76. this.reconnectTimeOut = setTimeout(()=>{
  77. this.connectSocketInit();
  78. },3000)
  79. }
  80. }
  81. }
  82. module.exports = websocketUtil