E
E
Enkei12019-03-27 18:56:32
JavaScript
Enkei1, 2019-03-27 18:56:32

How to send a websocket to a specific user?

Given:
Server side:

server.get('/updateData',  (req, res, next) => {
    if (!res.claimUpgrade) {
        next(new Error('Connection Must Upgrade For WebSockets'));
        return;
    }
    const upgrade = res.claimUpgrade();
    const shed = ws.accept(req, upgrade.socket, upgrade.head);

    shed.on('text', function (msg) {
        acceptedUsername = msg;
        console.log('User: ' + msg);
        const response = {
            username: acceptedUsername,
            msg: "Update"
        };
        shed.send(JSON.stringify(response));
    });

    next(false);
});

Client side:
authForSync.onopen = function (event) {
    console.log("Opened socket!");
    authForSync.send(user.username);
};

authForSync.onmessage = function (event) {
    if ((JSON.parse(event.data)).username === user.username) {
        console.log((JSON.parse(event.data)).username);
    }
    syncWithServer.close();
};

When the page is loaded, the nickname of the current user is sent to the server from the user object.
Task: when something happens on the server, let's say some event A, you need to send a specific message to a specific client with a specific username. Username is unique for each client. How to do it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
fukkit, 2019-03-27
@fukkit

You need to associate acceptedUsername and shed, for example, store them in a hash:
Further, to send a message to the client:
sheds[username].send(message)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question