How to send a websocket to a specific user?

This:
Server:
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);
});

The client part:
authForSync.onopen = function (event) {
 console.log("socket Opened!");
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 loads on the server is the nickname of the current user from the user object.
Problem: when on the server there is something, say an event And need to send to a particular client with a specific username of a specific message. Username is unique to each client. How to do it?
March 19th 20 at 08:53
1 answer
March 19th 20 at 08:55
You need to associate acceptedUsername and shed, for example storing them in a hash:
sheds[acceptedUsername] = shed
In the future, to send a message to the client:
sheds[username].send(message)

Find more questions by tags Node.jsJavaScript