前言

简单封装创建、连接websocket类

代码

  1. 封装创建ws类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    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);
    }
  2. 封装连接ws类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    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包 可以在断开连接后自动尝试重新建立连接