如何正确并完全关闭/重置 TcpClient 连接? [英] How to properly and completely close/reset a TcpClient connection?

查看:34
本文介绍了如何正确并完全关闭/重置 TcpClient 连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关闭或重置 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() 甚至将其设置为 null 但这不起作用.只有完全重新启动软件才能工作.

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)

这是一个处理通信的库.软件本身可以调用Controller类(代表硬件)的ResetConnection()方法.

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;
}

现在根据我在这里读到的内容,我应该使用 tcpClient.Dispose() 而不是= 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆