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

白昼怎懂夜的黑 提交于 2019-12-22 10:26:57

问题


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.


回答1:


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).



来源:https://stackoverflow.com/questions/33160697/why-doesnt-io-emit-work-in-process-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!