简体   繁体   中英

Why doesn't io.emit() work in process.on()?

I'm trying to apply this so that my server will tell the clients when it is closed. I don't understand why the server will not emit. It seems like the program closes before it gets a chance to emit, but console.log() works. I think my problem probably has to do with the synchronous nature of process.on as mentioned here , but honestly I don't understand enough about what (a)synchronous really means in this context. Also, I'm on Windows 7 if that helps.

  // catch ctrl+c event and exit normally
  process.on('SIGINT', function (code) {
    io.emit("chat message", "Server CLOSED");
    console.log("Server CLOSED");
    process.exit(2);
    });

I just started messing around with this stuff today so forgive my ignorance. Any help is greatly appreciated!

Full server code.

io.emit() is an asynchronous operation (you can say that it works in the background) and due to various TCP optimizations (perhaps such as Nagle's algorithm), your data may not be sent immediately.

process.exit() takes effect immediately.

You are likely shutting down your app and thus all resources it owns before the message is successfully sent and acknowledged over TCP.

One possible work-around is to do the process.exit(2) on a slight delay that gives the TCP stack a chance to send the data before you shut it down.

Another possibility is to just avoid that last chat message. The client will shortly see that the connection to the server was closed and that it cannot reconnect so it should be equipped to display that info to the user anyway (in cases of a server crash).

You could also consider turning off the Nagle algorithm which attempts to wait a short bit before sending data in case you immediately send some more data that could be combined into the same packet. But, to know whether that would work reliably, you'd have to test pretty thoroughly on appropriate platforms and it's possible that even turning this off wouldn't fix the issue since it is a race between the TCP stack to send out its buffered data and the shutting down of all resources owned by this process (which includes the open socket).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM