小巷 又弯又长 没有门 没有窗 我拿把旧钥匙 敲着厚厚的墙 —— 顾城《小巷》
在websocket实例化的时候,我们会绑定一些事件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 var ws = new WebSocket(url);ws.onclose = function ( ) { }; ws.onerror = function ( ) { }; ws.onopen = function ( ) { }; ws.onmessage = function (event ) { }
如果希望websocket连接一直保持,我们会在close或者error上绑定重新连接方法。
1 2 3 4 5 6 ws.onclose = function ( ) { reconnect(); }; ws.onerror = function ( ) { reconnect(); };
这样一般正常情况下失去连接时,触发onclose方法,我们就能执行重连了。
stackoverflow上的一种做法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 function connect ( ) { var ws = new WebSocket('ws://localhost:8080' ); ws.onopen = function ( ) { ws.send(JSON .stringify({ })); }; ws.onmessage = function (e ) { console .log('Message:' , e.data); }; ws.onclose = function (e ) { console .log('Socket is closed. Reconnect will be attempted in 1 second.' , e.reason); setTimeout (function ( ) { connect(); }, 1000 ); }; ws.onerror = function (err ) { console .error('Socket encountered error: ' , err.message, 'Closing socket' ); ws.close(); }; } connect();
使用第三方包 reconnecting-websocket 1 var ws = new ReconnectingWebSocket('ws://....' );
一些选项
1 var socket = new ReconnectingWebSocket(url, null , {debug : true , reconnectInterval : 3000 });
或者
1 2 3 var socket = new ReconnectingWebSocket(url);socket.debug = true ; socket.timeoutInterval = 5400 ;
https://stackoverflow.com/questions/22431751/websocket-how-to-automatically-reconnect-after-it-dies https://www.jianshu.com/p/dfde99d46ef4 https://github.com/joewalnes/reconnecting-websocket