index.tsx 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { Input } from 'antd'
  2. import { useRef, useEffect, useState } from 'react'
  3. enum ReadyState {
  4. '0' = '连接中',
  5. '1' = '正常',
  6. '2' = '断开中',
  7. '3' = '断开'
  8. }
  9. const Test = () => {
  10. const [state, setState] = useState({
  11. address: 'ws://192.168.1.26:9000/m/v1/mail/fanout/progress',
  12. status: ''
  13. })
  14. const [receviceMsg, setReceviceMsg] = useState([])
  15. const ws = useRef(null)
  16. useEffect(() => {
  17. const websokcet = new WebSocket(state.address)
  18. ws.current = websokcet
  19. }, [])
  20. useEffect(() => {
  21. if (ws.current) {
  22. ws.current.addEventListener('open', () => {
  23. setState({ ...state, status: ReadyState[1] })
  24. })
  25. ws.current.addEventListener('close', () => {
  26. setState({ ...state, status: ReadyState[3] })
  27. })
  28. ws.current.addEventListener('message', msg => {
  29. const newMsg = JSON.parse(msg.data)
  30. const newMsgList = [...receviceMsg, newMsg]
  31. setReceviceMsg(newMsgList)
  32. })
  33. }
  34. }, [ws.current])
  35. return (
  36. <div className="w-full h-full bg-hex-cccccc p-4 flex flex-row">
  37. <div>
  38. <Input
  39. placeholder="请输入ws地址"
  40. style={{ width: '450px' }}
  41. defaultValue="ws://192.168.1.26:9000/m/v1/mail/fanout/progress"
  42. onChange={e => setState({ ...state, address: e.target.value })}
  43. />
  44. <div>当前连接状态:{state.status}</div>
  45. </div>
  46. <div className="ml-4 border w-400px h-800px border-gray-400">
  47. {receviceMsg.map(item => (
  48. <div key={item.mail}>
  49. <span>{item.mail}</span>
  50. <span>{item.status}</span>
  51. </div>
  52. ))}
  53. </div>
  54. </div>
  55. )
  56. }
  57. export default Test