0

is it save to just add a property with a numerical id to a new websocket object and to identify a client with this id which was added by the server ?

server.js

//...
var a_o_websocket_client = []

o_websocket_server.on("connection", async function (o_websocket_client) {
  console.log(`a new o_websocket_client connected: ${o_websocket_client}`)
  o_websocket_client.n_id = a_o_websocket_client.length; // assign a new id
  a_o_websocket_client.push(o_websocket_client)
  o_websocket_client.on(
    "message", 
    async function(s_message){
        console.log(`this is the websocket with the id ${n_id}`)
    }
  )
  
});
//...
Jonas Frey
  • 65
  • 6
  • Does this answer your question? [Why is extending native objects a bad practice?](https://stackoverflow.com/questions/14034180/why-is-extending-native-objects-a-bad-practice) – jsejcksn Aug 24 '22 at 21:40
  • If you need iteration of socket connections, it might be better to store them in a [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) (to prevent the possibility of duplicates), or — if you need to associate some data to each socket — store each as a key in a [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) with the associated data at the value. – jsejcksn Aug 24 '22 at 21:42
  • oh i thought a client can only initialize one websocket connection to the same server, but now i tested to create multiple `new WebSocket("ws://localhost:3636")` and the server identifies each new connection as a unique new websocket, now i see why i need to handle the identification of each websocket client myself ... – Jonas Frey Aug 24 '22 at 22:35

0 Answers0