socket.js 2.3 KB

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