socket.js 2.2 KB

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