• react加入websocket


    1、首先创建一个公共的组件,封装websocket

    代码如下

    /**
     * 参数:[socketOpen|socketClose|socketMessage|socketError] = func,[socket连接成功时触发|连接关闭|发送消息|连接错误]
     * timeout:连接超时时间
     * @type {module.webSocket}
     */
    module.exports =  class webSocket {
        constructor(param = {}) {
            this.param = param;
            this.reconnectCount = 0;
            this.socket = null;
            this.taskRemindInterval = null;
            this.isSucces=true;
        }
        connection = () => {
            let {socketUrl, timeout = 0} = this.param;
            // 检测当前浏览器是什么浏览器来决定用什么socket
            if ('WebSocket' in window) {
                console.log('WebSocket');
                
                this.socket = new WebSocket(socketUrl);
            }
            else if ('MozWebSocket' in window) {
                console.log('MozWebSocket');
    
                this.socket = new MozWebSocket(socketUrl);
            }
            else {
                console.log('SockJS');
                
                this.socket = new SockJS(socketUrl);
            }
            this.socket.onopen = this.onopen;
            this.socket.onmessage = this.onmessage;
            this.socket.onclose = this.onclose;
            this.socket.onerror = this.onerror;
            this.socket.sendMessage = this.sendMessage;
            this.socket.closeSocket = this.closeSocket;
            // 检测返回的状态码 如果socket.readyState不等于1则连接失败,关闭连接
            if(timeout) {
                let time = setTimeout(() => {
                     if(this.socket && this.socket.readyState !== 1) {
                         this.socket.close();
                     }
                     clearInterval(time);
                }, timeout);
            }
        };
        // 连接成功触发
        onopen = () => {
            let {socketOpen} = this.param;
            this.isSucces=false  //连接成功将标识符改为false
            socketOpen && socketOpen();
        };
        // 后端向前端推得数据
        onmessage = (msg) => {
            let {socketMessage} = this.param;
            socketMessage && socketMessage(msg);
            // 打印出后端推得数据
            console.log(msg);
        };
        // 关闭连接触发
        onclose = (e) => {
            this.isSucces=true   //关闭将标识符改为true
            console.log('关闭socket收到的数据');
            let {socketClose} = this.param;
            socketClose && socketClose(e);
            // 根据后端返回的状态码做操作
            // 我的项目是当前页面打开两个或者以上,就把当前以打开的socket关闭
            // 否则就20秒重连一次,直到重连成功为止 
            if(e.code=='4500'){
                this.socket.close();
            }else{
                this.taskRemindInterval = setInterval(()=>{
                    if(this.isSucces){
                        this.connection();
                    }else{
                        clearInterval(this.taskRemindInterval)
                    }
                },20000)
            }
        };
        onerror = (e) => {
            // socket连接报错触发
            let {socketError} = this.param;
            this.socket = null;
            socketError && socketError(e);
        };
        sendMessage = (value) => {
            // 向后端发送数据
            if(this.socket) {
                this.socket.send(JSON.stringify(value));
            }
        };
    };

    2、在我们的react项目中引入这个公共的组件

    import Socket from './index';
    
    
    class websocket extends React.Component {
        constructor() {
            super();
            this.taskRemindInterval = null;
        }
        componentDidMount = () => {
            //    判断专家是否登录
            this.socket = new Socket({
                socketUrl: 'ws://123.207.167.163:9010/ajaxchattest',
                timeout: 5000,
                socketMessage: (receive) => {
                    console.log(receive);  //后端返回的数据,渲染页面
                },
                socketClose: (msg) => {
                    console.log(msg);
                },
                socketError: () => {
                    console.log(this.state.taskStage + '连接建立失败');
                },
                socketOpen: () => {
                    console.log('连接建立成功');
                    // 心跳机制 定时向后端发数据
                    this.taskRemindInterval = setInterval(() => {
                        this.socket.sendMessage({ "msgType": 0 })
                    }, 30000)
                }
            });
         重试创建socket连接
            try {
                this.socket.connection();
            } catch (e) {
                // 捕获异常,防止js error
                // donothing
            }
        }
    
    }
    
    export default websocket;
  • 相关阅读:
    设计模式目录
    垃圾收集器
    598. Range Addition II
    Java中的四种引用
    垃圾回收算法
    645. Set Mismatch
    java 8中撤销永久代,引入元空间
    L2-013. 红色警报 (并查集)
    POJ 1127 Jack Straws (线段相交)
    L2-014. 列车调度 (DP)
  • 原文地址:https://www.cnblogs.com/houjl/p/10812519.html
Copyright © 2020-2023  润新知