socket.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. import global from '@/utils/global.js'
  2. const baseSocketUrl=global.WebSocketUrl
  3. class socket {
  4. constructor(options) {
  5. //用户id
  6. this.sid=options.sid
  7. this.socketUrl=baseSocketUrl+options.sid
  8. this.socketStart = false;
  9. this.enableHeartbeat=true
  10. this.monitorSocketClose();
  11. this.socketReceive();
  12. this.monitorSocketError();
  13. }
  14. init(callback) {
  15. const _this = this;
  16. if (this.socketUrl) {
  17. if (this.socketStart) {
  18. console.log('webSocket已经启动了');
  19. } else {
  20. uni.connectSocket({
  21. url: this.socketUrl,
  22. method: 'GET'
  23. });
  24. uni.onSocketOpen((res) => {
  25. this.socketStart = true;
  26. callback && callback();
  27. console.log('WebSocket连接已打开!');
  28. });
  29. setTimeout(() => {
  30. _this.getHeartbeat();
  31. }, 5000);
  32. }
  33. } else {
  34. console.log('socketUrl为空');
  35. }
  36. }
  37. //Socket给服务器发送消息
  38. send(data, callback) {
  39. const _this = this;
  40. uni.sendSocketMessage({
  41. data: JSON.stringify(data),
  42. success: () => {
  43. callback && callback(true);
  44. },
  45. fail: () => {
  46. callback && callback(false);
  47. }
  48. });
  49. }
  50. //Socket接收服务器发送过来的消息
  51. socketReceive() {
  52. const _this = this;
  53. uni.onSocketMessage(function(res) {
  54. let data = JSON.parse(res.data);
  55. console.log('收到服务器内容:', data);
  56. _this.acceptMessage && _this.acceptMessage(data);
  57. });
  58. }
  59. //关闭Socket
  60. closeSocket() {
  61. const _this = this;
  62. uni.closeSocket();
  63. _this.socketStart = false;
  64. //关闭心跳
  65. _this.enableHeartbeat = false
  66. }
  67. //监听Socket关闭
  68. monitorSocketClose() {
  69. const _this = this;
  70. uni.onSocketClose(function(res) {
  71. console.log('WebSocket 已关闭!');
  72. _this.socketStart = false;
  73. if (_this.enableHeartbeat) {
  74. //开启心跳就自动重连
  75. setTimeout(()=>{
  76. _this.init()
  77. },3000)
  78. }
  79. });
  80. }
  81. //监听Socket错误
  82. monitorSocketError() {
  83. const _this = this;
  84. uni.onSocketError(function(res) {
  85. _this.socketStart = false;
  86. console.log('WebSocket连接打开失败,请检查!');
  87. _this.error && _this.error(res);
  88. });
  89. }
  90. //心跳
  91. getHeartbeat() {
  92. const _this = this;
  93. if (!this.enableHeartbeat) {
  94. //未开启心跳
  95. return
  96. }
  97. //开启心跳
  98. this.send({
  99. content: "心跳",
  100. sid:this.sid
  101. }, (val) => {
  102. setTimeout(() => {
  103. if (val) {
  104. _this.getHeartbeat();
  105. } else {
  106. _this.init();
  107. }
  108. }, 10000);
  109. });
  110. }
  111. }
  112. export default socket