0

Let's say I have a tcp server in nodejs and two clients connected (socket1 and socket2). So, when a data event is received from one, I want to write that to the other. As simple as that. The easiest would be to store socket1 in socket2 and vice versa. For example:

socket1.other=socket2;
socket2.other=socket1;

So, when socket1 sends data to server I can simply: socket1.other.write the data, but in that case socket1 would store a reference to socket2 which includes socket1 and this does not seem to work.

Is the only way to store both in an array and always loop through it to find the other socket when data needs to be sent?

Nordle
  • 2,915
  • 3
  • 16
  • 34
  • The server could store all its sockets in an array (or in an object rather, to have unique ids as keys) under a unique ID, and then you just store this ID instead of the whole socket. (The information of which socket you need to contact could be in this same array instead of in the socket, each socket would only need to store its unique ID) – Kaddath Apr 23 '19 at 08:05
  • What you are describing there is a circular reference. There is inherently nothing wrong about that. https://stackoverflow.com/q/1493453/8557739 – T Tse Apr 23 '19 at 08:07
  • Also, could you be more precise on "this does not seem to work"? As ShioT says, in JS circular references are not forbidden, maybe there's something else wrong in your code (sharing the relevant part of your code in the question itself could help) – Kaddath Apr 23 '19 at 08:10
  • Thank you I was searching for this as "cross reference" or "cross link" etc but now I know it's called circular reference. Is not this considered as bad desing? In the above example I can write as many "other" I want. For example socket1.other.other.other.other etc. – László T Apr 23 '19 at 08:18
  • Circular references are not a bad design "per se", when the case justifies it. In your case it doesn't seem necessary though, and having a general array for your server to store the open sockets with their relations seems a good choice – Kaddath Apr 23 '19 at 08:41

0 Answers0