socket.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import base from '@/config/baseUrl';
  2. import store from '@/store';
  3. class socket {
  4. constructor(options) {
  5. //地址
  6. this.socketUrl = base.socketUrl;
  7. this.socketStart = false;
  8. this.monitorSocketError();
  9. this.monitorSocketClose();
  10. this.socketReceive();
  11. }
  12. init(callback) {
  13. const _this = this;
  14. if (base.socketUrl) {
  15. if(this.socketStart){
  16. }else{
  17. uni.connectSocket({
  18. url: this.socketUrl,
  19. method: 'GET'
  20. });
  21. uni.onSocketOpen((res) => {
  22. this.socketStart = true;
  23. callback && callback();
  24. });
  25. setTimeout(() => {
  26. _this.getHeartbeat();
  27. }, 5000);
  28. }
  29. }else{
  30. }
  31. }
  32. //Socket给服务器发送消息
  33. send(data, callback) {
  34. const _this = this;
  35. if (store.state.userInfo.uid) {
  36. data.userUid = store.state.userInfo.uid;
  37. }
  38. uni.sendSocketMessage({
  39. data: JSON.stringify(data),
  40. success: () => {
  41. callback && callback(true);
  42. },
  43. fail: () => {
  44. callback && callback(false);
  45. }
  46. });
  47. }
  48. //Socket接收服务器发送过来的消息
  49. socketReceive() {
  50. const _this = this;
  51. uni.onSocketMessage(function(res) {
  52. let data = JSON.parse(res.data);
  53. console.log('收到服务器内容:', data);
  54. _this.acceptMessage && _this.acceptMessage(data);
  55. });
  56. }
  57. //关闭Socket
  58. closeSocket() {
  59. uni.closeSocket();
  60. _this.socketStart = false;
  61. }
  62. //监听Socket关闭
  63. monitorSocketClose() {
  64. const _this = this;
  65. uni.onSocketClose(function(res) {
  66. console.log('WebSocket 已关闭!');
  67. _this.socketStart = false;
  68. setTimeout(function() {
  69. _this.init();
  70. }, 3000);
  71. });
  72. }
  73. //监听Socket错误
  74. monitorSocketError() {
  75. const _this = this;
  76. uni.onSocketError(function(res) {
  77. _this.socketStart = false;
  78. console.log('WebSocket连接打开失败,请检查!');
  79. });
  80. }
  81. //心跳
  82. getHeartbeat() {
  83. const _this = this;
  84. this.send({
  85. type: "心跳",
  86. userUid: store.state.userInfo.userUid
  87. }, (val) => {
  88. setTimeout(() => {
  89. if (val) {
  90. _this.getHeartbeat();
  91. } else {
  92. _this.init();
  93. }
  94. }, 10000);
  95. });
  96. }
  97. };
  98. const mySocket = new socket();
  99. export default mySocket;