zoukankan      html  css  js  c++  java
  • 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;
  • 相关阅读:
    【转】浅谈MVC与三层架构
    【转】小结登录的几种交互方式
    【转】 App架构设计经验谈:接口的设计
    【转】JS编码解码、C#编码解码
    jQuery 判断是否包含某个属性
    jQuery on()方法
    常用正则表达式大全
    Fiddler 抓取手机APP数据包
    [Asp.net]通过uploadify将文件上传到B服务器的共享文件夹中
    ★电车难题的n个坑爹变种
  • 原文地址:https://www.cnblogs.com/houjl/p/10812519.html
Copyright © 2011-2022 走看看