Is the server side "connection" event emitted BEFORE the client receives the connection event? #4332
-
I am facing an issue, and I have a vague idea what is happening here, but I just want to ask, if I am correct in this: Right now, when a connection is made on my server, I am setting listeners on the socket server side, to accept some messages from the client, the following way:
It seems to me, that sometimes my client sends a request to the connected server, BEFORE the event listeners on the server side socket are set, and thus, some messages are lost. On the client side, I have a simmilar code:
What is the relation between the It seems to me, that the only place I should have access to the server side socket, BEFORE the connection event on the client side is sent, are the middlewares, but it doesn't seem to be a good fit, to set these listeners on. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
The "connection" event on the server side should be fired a bit earlier, because the client waits for a CONNECT packet (received in the long-polling HTTP request, or in a WebSocket frame). You should register the event listener in the "connection" handler, without any delay: io.on("connection", async (socket) => {
// BAD! "event" might be received while there is no listener
await fetchSomething();
socket.on("event", () => {});
}); I think |
Beta Was this translation helpful? Give feedback.
The "connection" event on the server side should be fired a bit earlier, because the client waits for a CONNECT packet (received in the long-polling HTTP request, or in a WebSocket frame).
You should register the event listener in the "connection" handler, without any delay:
I think
autoConnect: false
is not needed in your example above, becauseclientSideSocket.on()
will always be called before the connection (which involves I/O operations).