W
W
WebDev2019-02-05 10:46:26
JavaScript
WebDev, 2019-02-05 10:46:26

How to differentiate clients on websocket server in nodejs?

I'm trying to write a chat on websockets.
On the server, the code is:

const WebSocket = require('ws');

const server = new WebSocket.Server({port: 3001});

const activeClients = [];

server.on('connection', ws => {
    activeClients.push(ws);

    ws.on('close', data => {
        //Что мы тут полчаем? data = 1006
    });

    ws.on('message', message => {
       //Как отправить сообщение конкретному пользователю?
    });

});

Please tell me:
1) How can I distinguish clients? I did not find any unique field on the ws (on connection) object, like id. On the Internet they write that you need to add the id yourself.
2) How can I find out which client has disconnected? In the ws.on('message') event some number is returned. I didn't understand what it was.
3) How do I send a message to a specific user? This point follows from point 1.
4) Well, if there really is no default identifier, then why didn't they make it? Why don't they immediately generate the id and pass it to on('close')? That would have been very convenient.
Here are my crutches that work, but I'm not sure what I'm doing right:
const WebSocket = require('ws');

const server = new WebSocket.Server({port: 3001});

const activeClients = [];

function generateUniqueID() {
    //return some random string
}

server.on('connection', ws => {
    ws.uniqueID = generateUniqueID();//Костыль: Добавляем собственный ID

    activeClients.push(ws);

    ws.on('close', data => {
         //Костыль: знаем что кто-то отсоединился, проходимся по массиву клиентов и смотрим, у кого статус "отключен"
        activeClients.forEach(client, i => {
            if (client.readyState !== WebSocket.CLOSE) {
                activeClients.splice(i, 1);
            }
        });
    });

    ws.on('message', message => {
       //Костыль: получаем из message ID пользователя, которому нужно отправлить сообщение (toUserID) и отправляем ему, перебрав весь массив
       const data = JSON.parse(message);

        activeClients.forEach(client, i => {
            if (client.readyState === WebSocket.OPEN && client.uniqueID === data.toUserID) {
                client.send(...)//Сообщение конкретному пользователю.
            }
        });
    });

});

My crutches are working, please tell me, what are my mistakes? How to make it easier and more correct?
UPD:
Give some tutorial on how to create a real chat. In all lessons, a banal chat is created that receives a message and sends it to ALL other clients. I would like to see how they make more complex functionality.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Abcdefgk, 2019-02-05
@kirill-93

Well, uh ... you need to turn to the materiel. A clear case study is here ->

T
Taras Fomin, 2019-02-05
@Tarik02

I recommend looking towards socket.io

S
Sergey Grigoriev, 2019-02-05
@sedoyjan

I don't see a problem with storing connections under unique identifiers.
Only I use https://www.npmjs.com/package/uuid

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question