jonataslaw / dart-server-nano

A light, fast, and friendly server written in Dart.
MIT License
23 stars 4 forks source link

How to access to rooms collections from outside of socket scope? #9

Closed inyong1 closed 5 months ago

inyong1 commented 11 months ago

BTW what is the best way to beable to send message to a socket or a room from outside of socket scope, Let say we create a rest api route to send an event to a spesific room. Or let say we need to send sync event trigger to a connected socket of a room when some data in the database changed.

As for now my idea is to create a global list variable to keep connected socket. I use onOpen and onClose event to add and remove from the list. But I think this is not the best way because it create duplicate rooms collections.

jonataslaw commented 5 months ago

Well, your approach shouldn't work (not in the current version). In theory, everything related to the socket should be managed within the socket, since requests are executed within isolation. Dart has a limitation with isolates, where neither the Websockets class nor the HttpRequest can be sent by isolates. In the past there was a big problem when we used isolates and rooms, to be honest, this approach was impossible. If we have a room There is no way to send the websockets class via isolates, so it is not possible to delegate responsibility outside the isolate. So the only certainty we have is that this is not possible. After analyzing all possibilities, wasting more than 20 hours of my scarce time, analyzing hypotheses, talking to developers and AIs, I came to the conclusion that:

  1. This is impossible.
  2. There is a way around this, not ideal, but the only one currently available. Use just a single isolate for websockets, use a different port for the connection, and manage everything together at the library level. As it is still running within an isolate, the limitation continues, you cannot manage rooms from outside of it.

The only way to get around this would be to run it on the main thread, but this would harm anyone using the server on the mobile.

I can try to make this "configurable", but it will make the project more complex.