Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
663 views
in Technique[技术] by (71.8m points)

c# - How to properly and completely close/reset a TcpClient connection?

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.

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.

Suggestions?


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)

It's a library that handles communication. The software itself can call the ResetConnection() method of the Controller class (which represents the hardware).

It currently looks like

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to close the stream before closing the connection:

tcpClient.GetStream().Close();
tcpClient.Close();

Closing the client does not close the stream.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...