Webscoket 断线重连

2018-04-23  本文已影响0人  此昵称已被狗抢占
// 断线重连间隔
const reconnectInterval = 3000;

export default function ReconnectWebSocket(url) {
    let ws;
    let eventEmitter = new EventEmitter();

    (function connect() {

        ws = new WebSocket(url);
        ws.binaryType = "arraybuffer";

        ws.addEventListener('open', (e) => {
            eventEmitter.emit('open');
        });

        ws.addEventListener('message', (e) => {
            eventEmitter.emit('message', e);
        });

        ws.addEventListener('close', () => {
            eventEmitter.emit('close');
            console.log('WebSocket reconnecting...');
            setTimeout(connect, reconnectInterval);
        });

    })();

    eventEmitter.addListener('send', (msg) => {
        ws.send(msg);
    });

    eventEmitter.send = (msg) => {
        eventEmitter.emit('send', msg);
    }

    return eventEmitter;
};
上一篇 下一篇

猜你喜欢

热点阅读