How To Send Message Between Users With Same Token Using 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 will come fro
Solution 1:
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', functionconnection(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', functionincoming(message) {
if ('' === message) {
//skip if message is blankreturn;
}
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 emptyreturn;
}
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
<buttontype="button"id="sendBtn"class="btn-primary">Send</button><scripttype="text/javascript">const socket = newWebSocket('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>
Post a Comment for "How To Send Message Between Users With Same Token Using Websocket?"