稳定袜子
重新连接的网络套接字 .
安装
$ npm install @github/stable-socket
使用量
import {StableSocket} from '@github/stable-socket'
const delegate = {
socketDidOpen(socket: Socket) {
// Socket is ready to write.
socket.send('Hello')
},
socketDidClose(socket: Socket, code?: number, reason?: string) {
// Socket closed and will retry the connection.
},
socketDidFinish(socket: Socket) {
// Socket closed for good and will not retry.
},
socketDidReceiveMessage(socket: Socket, message: string) {
// Socket read data from the connection.
},
socketShouldRetry(socket: Socket, code: number): boolean {
// Socket reconnects unless server returns the policy violation code.
return code !== 1008
}
}
const policy = {
timeout: 4000,
attempts: Infinity,
maxDelay: 60000
}
const url = 'wss://live.example.com'
const socket = new StableSocket(url , delegate, policy)
socket.open()
缓冲套装
在打开状态或关闭状态时写入 StableSocket 丢弃信件数据。 使用缓冲Socket来缓冲写入 当它打开时发送.
import {BufferedSocket, StableSocket} from '@github/stable-socket'
const socket = new BufferedSocket(new StableSocket(url, delegate, policy))
socket.open()
socket.send('hello') // Will be sent when the socket is open.
同步连接
StableSocket 和 BufferedSocket 是对一个 WebSocket 的抽象化 维护内部的状态机器,管理重新连接和阻止写作 打开插座。 然而,有时我们需要直接访问一个开放的WebSocket 函数.
连接
同步连接到网络套接字端口, 或者在超时后失败 。 这个
套接字打开, 可写入 send当诺言实现的时候.
返回以打开的 WebSocket 实现的承诺或以拒绝方式拒绝的承诺
连接失败 .
import {connect} from '@github/stable-socket'
try {
const socket = await connect('wss://live.example.com', 100)
socket.send('hi')
} catch (e) {
console.log('Socket connection failed', e)
}
与 Retry 连接
同步连接到网络套接字端口, 重试失败的连接 以指数回放。 返回以打开的 WebSocket 实现的承诺 或以连接失败拒绝.
import {connectWithRetry} from '@github/stable-socket'
try {
const policy = {timeout: 100, attempts: Infinity, maxDelay: 60000}
const socket = await connectWithRetry('wss://live.example.com', policy)
socket.send('hi')
} catch (e) {
console.log('Socket connection failed', e)
}
发展
npm install
npm test
许可证
以麻省理工学院许可证分发。 详情见LICENSE.