'Confusion about websocket message routing
I have setup a websocket server on a website. The code is similar to the following:
const express = require('express');
const app = express();
var WebSocketServer = require('websocket').server;
var connectionArray = [];
var nextID = Date.now();
//...
// Start server...
var webServer = app.listen(process.env.PORT || port, function(request, response) { console.log(" Received request for " + new Date()); } );
console.log('Listening on port ' + port);
function originIsAllowed(origin) {
// This is where you put code to ensure the connection should
// be accepted. Return false if it shouldn't be.
return true;
}
console.log("***CREATING WEBSOCKET SERVER");
var wsServer = new WebSocketServer({
httpServer: webServer,
// You should not use autoAcceptConnections for production
// applications, as it defeats all standard cross-origin protection
// facilities built into the protocol and the browser. You should
// *always* verify the connection's origin and decide whether or not
// to accept it.
autoAcceptConnections: false
});
console.log("***CREATED WEBSOCKET SERVER");
console.log("***CREATING REQUEST HANDLER");
wsServer.on('request', function(request) {
console.log("Handling request from " + request.origin);
if (!originIsAllowed(request.origin)) {
request.reject();
console.log("Connection from " + request.origin + " rejected.");
return;
}
//Accept the request and get a connection.
var connection = request.accept("json", request.origin);
//Add the new connection to our list of connections.
console.log((new Date()) + " Connection accepted.");
connectionArray.push(connection);
//Send the new client its token;
connection.clientID = nextID;
nextID++;
var msg = {
type: "id",
id: connection.clientID
};
connection.sendUTF(JSON.stringify(msg)); //how is this message routed to the proper client???
//...
}); //wsServer.on 'request'
I am looking for clarification on how the websocket server determines how to send response messages. For example, if there are multiple 'client pages' that all are enabled to send messages to the server, then how is the server response made to the correct client (that sent the message). In other words, if 'client A' and 'client B' and 'client C' are all setup to send messages via websocket, how is the server configured to properly route messages from 'client A' back to 'client A', from 'client B' back to 'client B', and from 'client C' back to 'client C'...?
The command to send a message from the server "connection.sendUTF(JSON.stringify(msg));") does not seem to take a parameter to route to a particular client. Any information or clarification about this would be greatly appreciated. I thank you in advance.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
