原生 js + node 封装 WebSocket

js

class Socket {
    constructor(url) {
        this.socket = new WebSocket(url)
    }

    send(msg) {
        console.log(msg);

        if (this.socket.readyState === 1) {
            this.socket.send(JSON.stringify(msg))
        }

        this.socket.onmessage = (e) => {
            console.log(e.data);
        }
    }
}

Socket.getInstance = (() => {
    let instance;
    return (url) => {
        if (!instance) {
            instance = new Socket(url)
        }
        return instance
    }
})()

let webSocket = Socket.getInstance('ws://localhost:5500/')

let i = 1
setInterval(() => {
    webSocket.send(`第 ${i++} 条 webSocket`)
}, 1000);

node

// 安装 ws 模块:cnpm i ws -S
const WebSocketServer = require('ws').Server
let wss = new WebSocketServer({ port: 5500 })

wss.on('connection', (ws) => {
    ws.on('message', (msg) => {
        console.log(msg);
    })
    ws.send('client connected')
})

你可能感兴趣的:(javascript,node)