当前位置:   article > 正文

react封装一个webScoket请求_antd react websocket

antd react websocket

封装一个webScoket请求

创建文件webScoket.tsx写入

  1. import React, { Component } from 'react'
  2. import { message } from 'antd'
  3. import axios from 'axios'
  4. export default class index extends Component {
  5. render() {
  6. return (
  7. <></>
  8. )
  9. }
  10. websocket: WebSocket | undefined;
  11. componentDidMount(): void {
  12. let that = this;
  13. var websocket = null;
  14. //判断当前浏览器是否支持WebSocket,是则创建WebSocket
  15. if ('WebSocket' in window) {
  16. console.log('浏览器支持Websocket');
  17. websocket = new WebSocket(this.props.SocketURL);
  18. this.websocket = websocket;
  19. } else {
  20. message.error('当前浏览器 Not support websocket');
  21. }
  22. //连接发生错误的回调方法
  23. websocket.onerror = () => {
  24. console.log('WebSocket连接发生错误');
  25. message.error('WebSocket连接发生错误');
  26. };
  27. //连接成功建立的回调方法
  28. websocket.onopen = () => {
  29. const { getURL } = this.props;
  30. axios.get(getURL);
  31. };
  32. //接收到消息的回调方法
  33. websocket.onmessage = (event) => {
  34. console.log(event);
  35. if (event.data) {
  36. console.log(event.data);
  37. try {
  38. const data = event.data;
  39. const { onmessage } = this.props;
  40. onmessage && onmessage(data);
  41. }
  42. catch {
  43. console.log(event.data)
  44. }
  45. finally {
  46. }
  47. }
  48. };
  49. //连接关闭的回调方法
  50. websocket.onclose = () => {
  51. console.log('WebSocket连接关闭');
  52. };
  53. //如果websocket连接还没断开就关闭了窗口,后台server端会抛异常。
  54. //所以增加监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接
  55. window.onbeforeunload = function () {
  56. that.closeWebSocket();
  57. };
  58. }
  59. closeWebSocket() {
  60. if (this.websocket) {
  61. this.websocket?.close();
  62. }
  63. }
  64. componentWillUnmount() {
  65. this.closeWebSocket();
  66. }
  67. }

在另一个文件内 引入并调用

  1. import React, { Component, useEffect, useState } from 'react'
  2. import WebScoketUI from '@/components/webScoketUI'
  3. function index(){
  4. const [ListData, setListData] = useState([])
  5. const onmessage = (data) => {
  6. const data1 = JSON.parse(data);
  7. const keys = Object.keys(data1);
  8. let ListData = keys.map(item => {
  9. return { title: item, list: data1[item] }
  10. })
  11. setListData(ListData);
  12. }
  13. return(
  14. <WebScoketUI SocketURL='ws://10.143.12.7:8099/safeguard/websocket/crowd_counting'
  15. getURL='/websocket/socket/safeguard/sendMsg/crowd_counting'
  16. onmessage={onmessage}
  17. />
  18. )
  19. }
  20. export default index

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/770819
推荐阅读
相关标签
  

闽ICP备14008679号