为什么 io.emit() 在 process.on() 中不起作用?
Why doesn't io.emit() work in process.on()?
我正在尝试申请 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,但老实说,我对 (a)synchronous 在这种情况下的真正含义了解不够。另外,如果有帮助,我在 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);
});
我今天才开始弄这些东西,请原谅我的无知。非常感谢任何帮助!
io.emit()
是一个异步操作(你可以说它在后台工作)并且由于各种TCP优化(也许比如Nagle的算法),你的数据可能不会立即发送。
process.exit()
立即生效
在通过 TCP 成功发送和确认消息之前,您可能会关闭您的应用程序以及它拥有的所有资源。
一种可能的解决方法是稍微延迟执行 process.exit(2)
,让 TCP 堆栈有机会在您关闭它之前发送数据。
另一种可能性是避免最后一条聊天消息。客户端很快就会看到与服务器的连接已关闭并且无法重新连接,因此它应该能够向用户显示该信息(在服务器崩溃的情况下)。
您还可以考虑关闭 Nagle 算法,该算法会在发送数据之前尝试稍等片刻,以防您立即发送更多可以合并到同一个数据包中的数据。但是,要知道这是否会可靠地工作,您必须在适当的平台上进行非常彻底的测试,并且即使关闭它也可能无法解决问题,因为它是 TCP 堆栈之间发送其缓冲数据的竞赛并关闭此进程拥有的所有资源(包括打开的套接字)。
我正在尝试申请 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,但老实说,我对 (a)synchronous 在这种情况下的真正含义了解不够。另外,如果有帮助,我在 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);
});
我今天才开始弄这些东西,请原谅我的无知。非常感谢任何帮助!
io.emit()
是一个异步操作(你可以说它在后台工作)并且由于各种TCP优化(也许比如Nagle的算法),你的数据可能不会立即发送。
process.exit()
立即生效
在通过 TCP 成功发送和确认消息之前,您可能会关闭您的应用程序以及它拥有的所有资源。
一种可能的解决方法是稍微延迟执行 process.exit(2)
,让 TCP 堆栈有机会在您关闭它之前发送数据。
另一种可能性是避免最后一条聊天消息。客户端很快就会看到与服务器的连接已关闭并且无法重新连接,因此它应该能够向用户显示该信息(在服务器崩溃的情况下)。
您还可以考虑关闭 Nagle 算法,该算法会在发送数据之前尝试稍等片刻,以防您立即发送更多可以合并到同一个数据包中的数据。但是,要知道这是否会可靠地工作,您必须在适当的平台上进行非常彻底的测试,并且即使关闭它也可能无法解决问题,因为它是 TCP 堆栈之间发送其缓冲数据的竞赛并关闭此进程拥有的所有资源(包括打开的套接字)。