当前位置:   article > 正文

React 函数式组件使用Websocket_函数式组件实现webscoket

函数式组件实现webscoket

React 函数式组件使用Websocket

其实功能是比较简单,只要理解到hooks怎么在函数式组件工作的,就能写出来。同时,我觉得这几篇文章讲解hook非常好。
用动画和实战打开 React Hooks(一):useState 和 useEffect
下面直接上代码:

import SockJS from 'sockjs-client';
import { Subject } from 'rxjs';
export default class {
    get = new Subject();
    SocketApp: any = undefined;
    // 链接状态
    LinkConnected: boolean = false;
    // 重连超时计时器
    ReconnectTimer: any = null;
    HeartBeat: any = null;
    // 心跳计时器
    HeartBeatTimer: any = null;
    // 服务超时计时器
    $ServerTimer: any = null;
    reconnect() {
        if (this.LinkConnected) {
            return;
        }
        this.LinkConnected = true;
        this.ReconnectTimer = setTimeout(() => {
            console.info('websocket 尝试重连...');
            this.LinkConnected = false;
            this.createConnect();
        }, 5000);
    }
    /**
     *
     * @param url
     * 创建websocket对象
     */
    createConnect(url?: string) {
        if (!url) {
            url = `http://${window.location.host}/rest/websocket`;
        }
        this.SocketApp = new SockJS(url);
        this.SocketApp.onclose = () => {
            console.log('websocket 链接关闭');
            this.reconnect();
        };
        this.SocketApp.onopen = () => {
            console.info('websocket is open');
            // 心跳检查
            this.HeartBeatCheck();
        };
        this.SocketApp.onmessage = (data: any) => {
            const DATA = JSON.parse(data.data);
            if (DATA.type === 'wbs') {
                this.get.next(DATA);
            }
            // 心跳检查
            this.HeartBeatCheck();
        };
    }
    /**
     * 心跳检查
     */
    HeartBeatCheck() {
        if (this.HeartBeatTimer) {
            clearTimeout(this.HeartBeatTimer);
        }
        if (this.$ServerTimer) {
            clearTimeout(this.$ServerTimer);
        }
        this.HeartBeatTimer = setTimeout(() => {
            this.SocketApp.send('{"type":"heart"}');
            // 发送消息后10秒,没有响应,即代表websocket失去响应,10s后进入关闭程序
            this.$ServerTimer = setTimeout(() => {
                this.SocketApp.close();
            }, 10000);
        }, 10000);
    }
    Close() {
        if (this.SocketApp) {
            this.SocketApp.close();
            this.LinkConnected = true;
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
import WebsocketService from '@/services/websocket-service';
const $Websocket: any = useRef();
    const [SocketMsg, SetSocketMsg] = useState({});
    useEffect(() => {
        $Websocket.current = new WebsocketService();
        $Websocket.current.createConnect();
        return () => {
            $Websocket.current.Close();
        };
    }, []);
    useEffect(() => {
        $Websocket.current.get.subscribe((msg: any) => {
            console.log(msg);
        });
    }, [SocketMsg]);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

其中还可以使用消费全局的state的方式,待下次更新。

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

闽ICP备14008679号