美文网首页
React +Socket.io实现 网络实时推送消息

React +Socket.io实现 网络实时推送消息

作者: 微_______凉 | 来源:发表于2018-08-07 15:26 被阅读0次

    安装 socket.io

    npm install -save socket.io

    封装 socket,io 客户端

    /**

    • webSocket客户端工厂,目的在于使用facade模式封装关于webSocket的操作

    • 不涉及任何业务处理。

    • 实现方案:定义WebSocket类,该类具备发送消息和监听消息能力

    */

    
    export default class WebSocketClient {
    
    constructor(uri ='/', {
    
    path ='/',
    
    forceNew =true,
    
    transports = ['polling','websocket'],
    
    autoConnect =false,
    
    } = {}
    
    ){
    
    this.client = io(uri,{path, forceNew,transports,autoConnect});
    
    }
    
    connect(){
    
    this.client.open();
    
    }
    
    disconnect(){
    
    this.client.close();
    
    }
    
    receive(eventName,callback){
    
    this.client.on(eventName,(data) => callback(transJson(data)));
    
    }
    
    send(eventName,data){
    
    this.client.emit(eventName,data);
    
    }
    
    }
    
    /**
    
    * 将后台传过来的json字符串转换为object
    
    * @param data
    
    * @param callback
    
    */
    
    function transJson(data){
    
    let trans = data;
    
    if(typeof data ==='string' && (data.indexOf('{') ===0 || data.indexOf('[') ===0)){
    
    trans =JSON.parse(data);
    
    }
    
    return trans;
    
    }```
    
    引入WebSocketClient 
    
    import WebSocketClient from "../../utils/WebSocketClient";
    
    利用react钩子函数实现实时刷新
    
    componentDidMount() { this.connectWebSocket()}
    
    componentWillReceiveProps(){ this.initWebSocket() }
    
    componentWillUnmount() { this.closeWebSocket() }
    
    connectWebSocket=()=>{
    
    if(!window.webSocketClient)
    
    { window.webSocketClient = new WebSocketClient('ws://${‘服务器地址’}',{path:'/path'}); }
    
    const {webSocketClient} = window; webSocketClient.connect();
    
    webSocketClient.send('event','123');
    
    ]
    
    initWebSocket=()=>{
    
    if(!window.webSocketClient)
    
    { window.webSocketClient =  new WebSocketClient('ws://${‘服务器地址’}',{path:'/path'}); }
    
    const {webSocketClient} = window; webSocketClient.receive('
    
    Message',(data) =>{ this.setState({ socketData:data, }) });
    
    }
    
    closeWebSocket =()>{
    
     const {webSocketClient} = window;
    
    if(webSocketClient){ webSocketClient.disconnect();}
    
    }    
    
    
    
    

    相关文章

      网友评论

          本文标题:React +Socket.io实现 网络实时推送消息

          本文链接:https://www.haomeiwen.com/subject/qvhavftx.html