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;
