C语言 关闭客户端中的套接字会使 nodejs 服务器崩溃



在C客户端上,我做:

socket()
connect() on port 6969
send()
//I have seen that I didn't call recv so nodejs try me to send data but My program was gone
and finally closesocket()

在nodejs服务器上,我收到消息,因此建立了连接:

const port = 6969;
var net = require('net');
var server = net.createServer(function(connection) {
console.log('client connected');
connection.on('close', function() {
console.log('conn closed');
});
connection.on('end', function() {
console.log('conn ended');// that is not called
});
connection.on("error", function(err) {
console.log("Caught flash policy server socket error: ");
console.log(err.stack);
});
connection.on('data', function(data) {
data = data.toString();
console.log('client sended the folowing string:' + data);
connection.write("Response");
console.log('Sended response to client');
});
});
server.listen(port, function() {
console.log('server is listening');
});

这是我终端的结果:

server is listening
client connected
client sended the folowing string:err404
Sended response to client
Caught flash policy server socket error:
Error: read ECONNRESET
at exports._errnoException (util.js:1018:11)
at TCP.onread (net.js:568:26)
conn closed

所以我已经阅读了 Node js ECONNRESET 但我不明白这是否正常,为什么我的 nodejs 服务器崩溃?

编辑:我找到了这个片段:

connection.on("error", function(err) {
console.log("Caught flash policy server socket error: ");
console.log(err.stack);
});

客户端上的此代码将产生相同的错误:

#ifdef WIN32
Sleep(5000);
int iResult = shutdown(sock, SD_BOTH);
printf("shutdown is calledn");
Sleep(5000);
#elif defined (linux)
sleep(5);
int iResult = shutdown(sock, SHUT_RDWR);
printf("shutdown is calledn");
sleep(5);
#endif // WIN32
if (iResult == SOCKET_ERROR) {closesocket(sock);printf("SOCKET_ERROR");}
printf("iResult=%d",iResult);

编辑: 现在我捕获了关闭事件和结束事件:但仍然抛出相同的错误。

编辑:我已经更新了我的代码。 我发现问题出在哪里:NodeJs 试图向我发送数据,但我已经打电话给shutdown()

需要考虑两件事,一件在服务器中,另一件在客户端代码中。

服务器代码:

您必须使用end事件而不是close事件,请参阅 https://nodejs.org/api/net.html#net_event_end:

connection.on('end', function (){
console.log('client disconnected');
});

结束事件:

当套接字的另一端发送 FIN 数据包时发出,从而结束套接字的可读侧。

关闭事件:

在套接字完全关闭后发出。参数 had_error 是一个布尔值,表示套接字是否由于传输错误而关闭。

这意味着,close事件将在end事件之后发生。


客户端代码:

您必须在关闭套接字之前调用shutdown以防止进一步的读取或写入,这会导致错误,因为套接字已经关闭。

shutdown的Windows版本在MSDN中描述,Linux变体在手册页中描述。

窗户:

int ret = shutdown(sockfd, SD_BOTH); /* Shutdown both send and receive operations. */

Linux:

int ret = shutdown(sockfd, SHUT_RDWR); /* Disables further send and receive operations. */

刷新已发送数据的重要性:

shutdown函数不保证不会发送缓冲区中已有的数据。在调用close之前,需要刷新所有数据。在这个关于SO的答案中,写下了一种很好的方法来做到这一点,而不仅仅是睡眠20毫秒左右。
为了测试这是否是您的问题,您可以使用 Windows 中的Sleep(2000)和 Linux 中的sleep(2)shutdownclose之间休眠 2 秒。


在此页面上,close/closesocketshutdown之间的一个很好的比较:

你已准备好关闭套接字描述符上的连接。这很容易。你可以只使用常规的Unix文件描述符close((函数:

close(sockfd); 

这将防止对套接字进行任何进一步的读取和写入。任何尝试在远程端读取或写入套接字的人都会收到错误。

如果你想对套接字的关闭方式有更多的控制,你可以使用 shutdown(( 函数。它允许您切断某个方向的通信,或两种方式(就像close((一样(。概要:

int shutdown(int sockfd, int how);

[...]

shutdown(( 在成功时返回 0,在错误时返回 -1(相应地设置 errno(。

最新更新