创建WebSocket连接时如何从Express Server中的客户端获取ID?

时间:2019-11-13 11:47:50

标签: javascript node.js websocket

我用websocket来表示客户端和服务器。

我在客户端上具有唯一ID(id = xxxxxxx)

当我在客户端上创建新的WebSocket连接时,如何在服务器上获取此ID?

客户:

let socket = new WebSocket("ws://localhost:7000");

服务器:

const webSocketServer = new WebSocket.Server({ server });
webSocketServer.on("connection", async (ws) => {

    ws.getUniqueID = function () {
        function s4() {
            return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
        }
        return s4() + s4() + '-' + s4();
    };
    ws.id = ws.getUniqueID()
    ws.isAlive = true;
    ws.on('pong', () => {
        ws.isAlive = true;
    });
    ws.on('message', async function(message) {
        let req = JSON.parse(message)
        switch (req['type']) {
            case 'phone':
                break
            case 'code':
                break
            default:
                break
        }
    });
    ws.onclose = function(event) {
        if (event.wasClean) {

        } else {

        }

    };
    ws.onerror = function(error) {

    };
    clients.saveClient(ws.id, ws)
});

1 个答案:

答案 0 :(得分:0)

async function getCookie(cookie, name) {
    let value = "; " + cookie;
    let parts = value.split("; " + name + "=");
    if (parts.length == 2) return parts.pop().split(";").shift();
}
webSocketServer.on("connection", async (ws, req) => {
    const ip = req.connection.remoteAddress;
    let id = await getCookie(req.headers['cookie'], 'name')...