useWebsocket.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /** 创建websocket */
  2. import { onUnmounted } from 'vue';
  3. import { useUserStore } from '@/store/modules/user';
  4. interface Params {
  5. msg: string;
  6. url?: string;
  7. }
  8. export const useWebsocket = (onMessage: (data: string) => unknown) => {
  9. const userStore = useUserStore();
  10. let ws: WebSocket;
  11. function start({ msg, url }: Params) {
  12. console.log('start msg', msg);
  13. console.log({ url });
  14. const defaultUrl = `/skyeye/${userStore.info.userId}`;
  15. const path = url || defaultUrl;
  16. ws = new WebSocket(
  17. `${window.location.protocol.includes('https') ? 'wss://' : 'ws://'}${
  18. window.location.host
  19. }/ws_api_bak${path}`,
  20. );
  21. //ws = new WebSocket(`ws://172.16.23.144:8800${path}`);
  22. ws.onmessage = function (e) {
  23. console.log('wx onmessage send params', msg);
  24. console.log('ws onmessage from server: ' + e.data);
  25. const data = e.data;
  26. onMessage(data);
  27. };
  28. ws.onopen = () => {
  29. if (msg) {
  30. ws.send(msg);
  31. }
  32. };
  33. }
  34. function close() {
  35. // console.log("ws unmounted", msg);
  36. ws?.close();
  37. }
  38. onUnmounted(() => {
  39. close();
  40. });
  41. return { start };
  42. };
  43. export default useWebsocket;