天天看點

原生 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')
})
           

繼續閱讀