Node websocket简单封装

前言

简单封装创建、连接websocket类

代码

  1. 封装创建ws类
const websocket = require('ws');
class WebSocket {
    constructor(options) {
        this.init();
        this.options = options;
    }

    init() {
        this.obj = {};
        this.options = {};
    }

    createServer(options) {
        const WS = new websocket.Server(this.options);
        WS.on('connection', (ws, req) => this.connection(ws, req))
    }

    async connection(ws, req) {
        console.log('建立连接', req.url);
        const id = req.url.split('/')[1];
        if (!id) return ws.close();
        this.obj[id] = ws;
        ws.id = id;
        this.filter();
        this.printObj();
        ws.send(JSON.stringify({data: '欢迎访问!', id: id}));

        ws.on('message', this.message);
        ws.on('close', (msg) => this.close(msg, ws.id));
    }

    async filter() {
        for(let key in this.obj) {
            if (!this.obj[key].readyState === 1) delete this.obj[key]
        }
    }

    async message(msg) {
        const message = JSON.parse(msg);
        console.log('接收消息', message);
    }

    close(msg, id) {
        console.log('关闭连接', id, msg);
    }

    send(msg, id) {
        if(id) {
            if (this.obj[id].readyState === 1) {
                this.obj[id].send(JSON.stringify(msg));
            }
        } else {
            for (let ws of Object.values(this.obj)) {
                if (ws.readyState === 1) ws.send(JSON.stringify(msg));
            }
        }
    }

    printObj() {
        console.log('---ws list---');
        for(let key in this.obj) {
            if (this.obj[key].readyState === 1) console.log(key);
        }
        console.log('----------');
    }
}

// create instance
let ws = new WebSocket({port: 3000});
try {
    ws.createServer();
    // ws.printObj();
} catch (err) {
    console.log(err);
}
  1. 封装连接ws类
const ReconnectingWebSocket = require('reconnecting-websocket');
const websocket = require('ws');
const EventEmitter = require('events').EventEmitter;

class ConnectWebSocket extends EventEmitter{
    constructor(url) {
        super();
        this.url = url;
        this.init();
    }

    init() {
        this.ws = null;
    }

    connectServer(type, listener) {
        this.ws = new ReconnectingWebSocket(this.url, [], {
            maxReconnectionDelay: 5000,
            WebSocket: websocket
        });
        this.ws.addEventListener('open', this.open);
        this.ws.addEventListener('close', this.close);
        this.ws.addEventListener('message', this.message);
    }

    open() {
        console.log('连接成功');
    }

    close() {
        console.log('连接已断开');
    }

    message(msg) {
        let message = JSON.parse(msg.data);
        console.log('接受消息', message);
    }

    send(msg) {
        this.ws.send(JSON.stringify(msg));
    }
}

// create instance
let connect = new ConnectWebSocket('ws://localhost:3000/1');
connect.connectServer();
connect.send('hello ws');

总结

  1. reconnecting-websocket npm包 可以在断开连接后自动尝试重新建立连接
posted @ 2020-04-26 09:20  落叶&不随风  阅读(680)  评论(0编辑  收藏  举报