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.
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);
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 code
<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>