如何正确和完全关闭/重置一个TcpClient的连接? [英] How to properly and completely close/reset a TcpClient connection?
问题描述
什么是关闭或重置一个TcpClient的连接的正确方法是什么? 我们的软件与硬件,但有时一些沟通 出了问题,我们不再与它交流,直到我们重新启动软件。
What is the correct way to close or reset a TcpClient connection? We have software that communicates with hardware but sometimes something goes wrong and we are no longer to communicate with it, until we restart the software.
我试图迫使TcpClient.Close(),甚至将其设置为空,但不起作用。 软件只能一个完整的重新启动。
I have tried forcing TcpClient.Close() and even setting it to null but that doesn't work. Only a complete restart of the software works.
建议?
我不能使用using关键字,因为TpcClient只在一个位置定义,而且在整个库中使用。 (而且只有一个在任何给定时间连接)
I can't use the using keyword because TpcClient is only defined in one location, but used throughout the library. (And there is only one connection at any given time)
这是处理通信库。软件本身可以调用控制器类的ResetConnection()方法(它重新presents硬件)。
It's a library that handles communication. The software itself can call the ResetConnection() method of the Controller class (which represents the hardware).
目前,它看起来像
if (tcpClient != null)
{
tcpClient.Close();
tcpClient = null;
}
现在从我读到这里,我应该使用,而不是=空
Now from what I've read here I should use tcpClient.Dispose() instead of " = null"
我会给一个尝试,看看它是否有差别。
I'll give that a try and see if it makes a difference.
推荐答案
您必须关闭连接前关闭流:
You have to close the stream before closing the connection:
tcpClient.GetStream().Close();
tcpClient.Close();
关闭客户端不会关闭该流。
Closing the client does not close the stream.
这篇关于如何正确和完全关闭/重置一个TcpClient的连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!