一个强大的可重新连接的 WebSocket 客户端,适用于浏览器
robust-websocket is a wrapper around the standard WebSocket class that implements the same interface, but can reconnect when disconnected or the user's computer comes back online.
It is error-code aware and will not reconnect on 1008 (HTTP 400 equivalent) and 1011 (HTTP 500 equivalent) by default. This behavior is fully configurable via the shouldConnect (see Usage).
Use it as you would a normal websocket:
var ws = new RobustWebSocket('ws://echo.websocket.org/')
ws.addEventListener('open', function(event) {
ws.send('Hello!')
})
ws.addEventListener('message', function(event) {
console.log('we got: ' + event.data)
})But with an optional set of options you can specify as a 3rd parameter
…shouldReconnect ExamplesReconnect with an exponetial backoff on all errors
function shouldReconnect(event, ws) {
return Math.pow(1.5, ws.attempts) * 500
}Reconnect immediately but only 20 times per RobustWebSocket instance
function shouldReconnect(event, ws) {
return ws.reconnects <= 20 && 0
}Reconnect only on some whitelisted codes, and only 3 attempts, except on online events, then connect immediately
function shouldReconnect(event, ws) {
if (event.type === 'online') return 0
return [1006,1011,1012].indexOf(event.code) && [1000,5000,10000][ws.attempt]
}See documentation for CloseEvent and online event, the two types of events that shouldReconnect will receive.
Typically, websockets closed with code 1000 indicate that the socket
closed normally. In these cases, robust-websocket won't call
shouldReconnect (and will not attempt to reconnect), unless you set
shouldReconnect.handle1000 to true.
You may need these polyfills to support older browsers
暂无开放 Issues,或尚未同步最近议题。