I work with sockjs. When a stream object (client) arrives, I send it through a worker to the master process.

process.send({ client: connection }) 

connection is a stream object (client).

And when I call the send method I get an error:

 internal/child_process.js:609 var string = JSON.stringify(message) + '\n'; ^ TypeError: Converting circular structure to JSON` 

With normal objects, everything is fine. Tell me how to fix it?

  • Are we talking about socket.io clients or something else? - Dmitriy Simushev
  • Yes, more precisely about sockjs. - ilez
  • This is not the same thing. If memory serves me, in the case of socket.io, you can easily share clients between processes using redis to store shared data. At the same time, of. Documentation recommends working with a client from the process that established communication with it. This is necessary for proper operation of the connection polyfiles. - Dmitriy Simushev
  • And how to make sure that they are not lost do not know? - ilez
  • In the framework of sockjs - I do not know. On the other hand, this is not important, as long as you have an external load balancer and work with the connection is concentrated in the worker. - Dmitriy Simushev

3 answers 3

As part of your approach to fix the problem will not work.

In fact, all that you can pass between processes is strings. Hence the implicit method call JSON.stringify , which turns the object into a string.

When it comes to some "living" objects that have not only fields but also behavior (event handlers, connections with other objects, etc.), even if you can successfully serialize an object, you still won't succeed restore it in another process.

Even if you managed to transfer the object to a completely different process without serialization, you would still lose all its connections, the connected handlers, etc., during the transfer. All this would simply remain in the work process.

As for the error, this is just a mention of cyclic references in the object being serialized. This is just one of the consequences of the problem indicated above.

    Greetings.

    Judging by an error when converting a connection to a string, looping occurs.

    An example of such an object:

     a = {} b = { "a": a } ab = b; JSON.stringify(a); // выдаст ошибку JSON.stringify(b); // тоже выдаст ошибку 

    Solution: to transfer not the entire connection but only the part with which to work

    • Comments are not intended for extended discussion; conversation moved to chat . - Nick Volynkin

    I learned how to solve the problem. When I run the child process, I give the number to this process. When a client comes in a socket, I send its ID and process number to the main process.