扫一扫分享
Sockette是一个很小的(348字节)包装器WebSocket,如果连接丢失,它将自动重新连接!
Sockette还允许您重用实例,从而无需重新声明所有事件侦听器。 您可以直接访问WebSocket每个EventListener回调(via event.target)中的(当前)底层。
sockette安装
npm install --save sockette
sockette使用
const Sockette = require('sockette');
const ws = new Sockette('ws://localhost:3000', {
timeout: 5e3,
maxAttempts: 10,
onopen: e => console.log('Connected!', e),
onmessage: e => console.log('Received:', e),
onreconnect: e => console.log('Reconnecting...', e),
onmaximum: e => console.log('Stop Attempting!', e),
onclose: e => console.log('Closed!', e),
onerror: e => console.log('Error:', e)
});
ws.send('Hello, world!');
ws.json({type: 'ping'});
ws.close(); // graceful shutdown
// Reconnect 10s later
setTimeout(ws.reconnect, 10e3);
手机预览