简体   繁体   English

为什么io.emit()在process.on()中不起作用?

[英]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. 程序似乎在有机会发射之前就关闭了,但是console.log()起作用了。 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. 我想我的问题可能有提到与process.on的同步特性做这里 ,但老实说,我不明白有足够的了解什么(一)同步的真正含义在这方面。 Also, I'm on Windows 7 if that helps. 另外,如果有帮助,我使用Windows 7。

  // 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. io.emit()是一个异步操作(可以说它在后台运行),并且由于各种TCP优化(例如Nagle的算法),您的数据可能不会立即发送。

process.exit() takes effect immediately. process.exit()立即生效。

You are likely shutting down your app and thus all resources it owns before the message is successfully sent and acknowledged over TCP. 在通过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. 一种可能的解决方法是在稍微延迟的情况下执行process.exit(2) ,这会使TCP堆栈有机会在关闭数据之前发送数据。

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. 您还可以考虑关闭Nagle算法,该算法会尝试在发送数据之前等待一会儿,以防您立即发送更多可以组合到同一数据包中的数据。 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). 但是,要知道它是否可靠地工作,您必须在适当的平台上进行彻底的测试,而且即使将其关闭也可能无法解决该问题,因为这是TCP堆栈之间发送其缓冲数据的竞赛并关闭此进程拥有的所有资源(包括打开的套接字)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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