socket.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import {getWssApiUrl} from "@/config/envApi";
  2. import {getStorage} from "@/utils/storage";
  3. import {getObjVal, getObjValue, isString} from "js-fast-way";
  4. import {useAppStore} from "@/store";
  5. export default class HcSocket {
  6. static socketTask = null
  7. static timeID = null
  8. static isConnect = false
  9. static initSocket() {
  10. let _this = this;
  11. this.timeID = setInterval(() => {
  12. if (!_this.isConnect) {
  13. const { user_id } = getObjValue(getStorage('userInfo'))
  14. if (!user_id) return false;
  15. _this.connectSocket(user_id)
  16. } else {
  17. clearInterval(_this.timeID)
  18. }
  19. }, 3000)
  20. }
  21. static connectSocket(user_id) {
  22. const _this = this, store = useAppStore();
  23. this.socketTask = uni.connectSocket({
  24. url: getWssApiUrl() + user_id,
  25. success: ()=> {
  26. console.log('socket 连接成功')
  27. },
  28. fail: () => {
  29. console.log('socket 连接失败')
  30. }
  31. });
  32. //连接已打开
  33. this.socketTask.onOpen(function(res) {
  34. console.log('socket 连接已打开');
  35. _this.isConnect = true
  36. const projectId = getStorage('projectId')
  37. const contractId = getStorage('contractId')
  38. _this.sendSocketMsg(`${projectId},${contractId}`)
  39. })
  40. //连接失败
  41. this.socketTask.onError(function(res) {
  42. console.log('socket 连接打开失败,请检查!');
  43. })
  44. //监听连接关闭
  45. this.socketTask.onClose((e) => {
  46. console.log('socket 连接关闭!');
  47. //进入重新连接
  48. setTimeout(() => {
  49. _this.connectSocket();
  50. }, 3000)
  51. })
  52. //收到的消息
  53. this.socketTask.onMessage(function({data}) {
  54. const countData = isString(data) ? JSON.parse(data) : {}
  55. if (getObjVal(countData)) {
  56. console.log('收到服务器内容:', countData);
  57. store.setMsgCountData(countData)
  58. }
  59. });
  60. }
  61. //发送消息
  62. static sendSocketMsg(msg) {
  63. this.socketTask.send({data: msg});
  64. }
  65. }