如何使用websocket在具有相同令牌的用户之间发送消息? [英] How to send message between users with same token using websocket?

查看:36
本文介绍了如何使用websocket在具有相同令牌的用户之间发送消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从 HTML 文件我使用 webSocket 发送消息.

From the HTML file I am sending message using webSocket.

const socket = new WebSocket("ws://localhost:3000/{{ token }}");
socket.send(JSON.stringify(message));

token 将来自浏览器 URL.

token will come from browser URL.

const WebSocket = require('ws');
const qs = require('querystring');
const http = require('http');
const wss = new WebSocket.Server({ port: 3000 });
const webSockets = {};


wss.on('connection', function (ws, req)
{
    let url = req.url;
    let userToken = url.substring(url.lastIndexOf('/') + 1);
    webSockets[userToken] = ws;
    
    ws.on('message', function incoming(message)
    {
        let messageArray = JSON.parse(message);
        let token = messageArray['token'];
        let toUserWebSocket = webSockets[token];
        toUserWebSocket.send(message);

我用以下网址打开了 3 个浏览器

I have opened 3 browsers with following URL

`https://url/same_token`
`https://url/same_token`
`https://url/different_token`

所有浏览器都在接收消息.如果消息是从 send_token 发送的,我希望消息只能由带有 same_token

Messages are being received in all browsers. If message is send from send_token I want message to be received only by browser with same_token

推荐答案

我无法按照所描述的那样重现该问题,但只能接收发送到具有相同 的已连接客户端之一的消息令牌.

I was not able to reproduce the issue as described, but was only able to receive the sent message to only one of the connected clients with the same token.

单个连接客户端的问题是由于引用了 webSockets[userToken] = ws,而不是使用客户端数组 webSockets[userToken] = [];code> 和 webSockets[userToken].push(ws);

The issue with the single connected client is due to webSockets[userToken] = ws being referenced, as opposed to using an array of clients webSockets[userToken] = []; and webSockets[userToken].push(ws);

还要确保您没有在后台运行的 node server.js 僵尸进程.

Also be sure that you do not have a zombie process of node server.js running in the background.

//...

const clients = {};

wss.on('connection', function connection(ws, req) {
    let id = req.url.substring(req.url.lastIndexOf('/') + 1);
    if ('' === id) {
        //connecting id is missing
        ws.terminate();

        return;
    }
    if ('undefined' === typeof clients[id]) {
        clients[id] = [];
    }
    console.log('Connection Received from IP: ' + req.socket.remoteAddress + ' with id ' + id);

    //append websocket client to list of clients
    clients[id].push(ws);

    ws.on('message', function incoming(message) {
        if ('' === message) {
            //skip if message is blank
            return;
        }

        try {
            //process message as JSON object as "{"message": "string", "token": "string"}"
            message = JSON.parse(message);
        } catch(e) {
            return;
        }

        if (!message.hasOwnProperty('token') || '' === message.token) {
            //token was not sent or is empty
            return;
        }
        let token = message.token;
        console.log('Message received for token ' + token);

        if ('undefined' !== typeof clients[token] && clients[token]) {
            clients[token].forEach(function(client) {
                if (client !== ws && client.readyState === WebSocket.OPEN) {
                    //do not send message back to the sending client
                    client.send(message.message + ' ' + token);
                }
            });
        }

        //inform sending client message was sent
        ws.send('Sent: ' + message.message);
    });

    ws.on('close', function() {
        clients[id].forEach(function(client, index) {
            if (client === ws) {
                //remove the client from the pool
                clients[id].splice(index, 1);
            }
        });
    });
});

html 代码

<button type="button" id="sendBtn" class="btn-primary">Send</button>

<script type="text/javascript">
    const socket = new WebSocket('ws://localhost:8080/{{ token }}');
    socket.onmessage = function(evt) {
        window.console.log(evt.data);
    };

    jQuery(function($) {
        $('#sendBtn').on('click', function() {
            const message = {
                "message": "Hello World",
                "token": "{{ token }}"
            };
            socket.send(JSON.stringify(message));
        });
    });
</script>

这篇关于如何使用websocket在具有相同令牌的用户之间发送消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆