useWebSocketFn.tsx 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /* eslint-disable react-hooks/rules-of-hooks */
  2. import { useWebSocket } from 'ahooks'
  3. import { notification } from 'antd'
  4. import { useEffect } from 'react'
  5. import { useModel } from 'umi'
  6. export enum cmdType {
  7. Single = 10,
  8. Group = 11,
  9. OnlineList = 12,
  10. Notice = 13
  11. }
  12. export enum noticeType {
  13. Notice = 1,
  14. Message = 2
  15. }
  16. // function noticeHandler (op) {}
  17. // function cmdReducer(cmd: cmdType, op: any) {
  18. // switch (cmd) {
  19. // case 13:
  20. // break
  21. // default:
  22. // break
  23. // }
  24. // }
  25. export default function useWebSocketFn() {
  26. const { initialState } = useModel('@@initialState')
  27. const { currentUser } = initialState
  28. const { disconnect, connect, webSocketIns, readyState } = useWebSocket(
  29. `ws://cld2qa.com/summon/v1/chat/link?username=${currentUser?.username}&id=${currentUser?.staffId}`,
  30. {
  31. manual: true,
  32. reconnectLimit: 3,
  33. reconnectInterval: 2000,
  34. onMessage: (message: WebSocketEventMap['message']) => {
  35. const data = message && JSON.parse(message.data)
  36. // console.log('data', data)
  37. // cmdReducer(data.cmd)
  38. if (data.cmd === cmdType.Notice) {
  39. notification.warning({
  40. message: '有新的版本更新, 请及时刷新页面',
  41. description: data.title,
  42. duration: null,
  43. btn: (
  44. <span
  45. className="text-primary cursor-pointer hover:text-hex-967bbd"
  46. onClick={() => window.location.reload()}
  47. >
  48. 点击刷新
  49. </span>
  50. )
  51. })
  52. }
  53. }
  54. }
  55. )
  56. useEffect(() => {
  57. if (currentUser && currentUser.staffId) {
  58. connect()
  59. console.log('readyState', readyState)
  60. }
  61. return () => {
  62. disconnect()
  63. }
  64. }, [])
  65. function sendMsg(cmd: cmdType, dstid?: string | null, media?: number | null, options: any) {
  66. webSocketIns?.send(
  67. JSON.stringify({ cmd, dstid, media, userid: currentUser.staffId, ...options })
  68. )
  69. }
  70. return { webSocketIns, sendMsg }
  71. }