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

2018-08-07  本文已影响0人  微_______凉

安装 socket.io

npm install -save socket.io

封装 socket,io 客户端

/**

*/


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();}

}    



上一篇下一篇

猜你喜欢

热点阅读