Jam*_* MA 6 c# sockets connection tcpclient
I'm now working on a tcp socket connection to tcp server running in ESP32. It works fine for the communication, but I failed to close the connection. After searching for the solution on close/reset tcpClient, it seems that the proper way to close a tcpClient should be:
tcpClient.GetStream().Close();
tcpCLient.Close();
Run Code Online (Sandbox Code Playgroud)
The example in msdn also use this method.
But unforunately, it cannot really close the connection. As checked in the mcu, the connection has not been closed. And it will not be closed even I close the application later. In this case, the mcu's tcp connection cannot be released, it cannot receive other connections. So, I think this should not be a proper solution to close the tcpClient.
If I did not execute above statement, and close the application directly, it can close the connection successfully. And the mcu's tcp connection is released. It seems that the there has something been done in application close which can really close the connection.
In some situation, I need to close the connection after some operation, and reconnect it. So, I cannot rely on the application close.
我已经以不同的组合尝试了以下所有方法,但没有一个可以成功释放 tcpClient 连接:
tcpClient.Close();
tcpClient.Client.Close();
tcpClient.GetStream().Close();
tcpClient.Client.Disconnect(true);
tcpClient.Client.Disconnect(false);
tcpClient.Dispose();
tcpClient.Client.Dispose();
tcpCLient = null;
Run Code Online (Sandbox Code Playgroud)
也许应该以适当的顺序使用上述一些命令来完成。
有谁知道我不能自己关闭连接。
提前致谢。
使用WireShark研究网络数据包后,发现问题是由于发送RST的延迟造成的,代码如下MSDN中建议的:
tcpClient.GetStream().Close();
tcpCLient.Close();
Run Code Online (Sandbox Code Playgroud)
即使添加也没有什么不同
tcpClient.LingerState = new LingerOptions(true, 0);
Run Code Online (Sandbox Code Playgroud)
因为Close方法后会立即发送FIN,但不会发送RST,所以会在2分钟左右发送。不幸的是,即使您在发出 tcpClient close 后关闭应用程序,也不会发送该消息。
如果您在关闭 tcpClient 之前关闭应用程序,它将立即发送 RST。
这样它就可以立即关闭与服务器的连接。
经过测试不同的命令组合,发现下面的代码确实可以立即关闭连接,但大约40秒后会有另一个RST。
tcpClient.Client.Close();
tcpClient.Close();
Run Code Online (Sandbox Code Playgroud)
不要调用 tcpClient.GetStream().Close(); !!!这会导致RST的延迟。
我不知道以这种方式关闭连接是否有任何影响,但这是我真正可以立即关闭连接的唯一方法。