• 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包 可以在断开连接后自动尝试重新建立连接
  • 相关阅读:
    JS和jQuery获取节点的兄弟,父级,子级元素
    HTTP协议详解
    HTML5自定义属性对象Dataset
    当你输入一个网址后都发生什么
    javascript实现ajax
    第一次项目总结
    CSS简单布局总结
    animate.css总结
    自定义动画
    CSS 第四天 多重背景 变形 过渡
  • 原文地址:https://www.cnblogs.com/xpengp/p/12762442.html
Copyright © 2020-2023  润新知