如何正确关闭TcpClient [英] How to properly close a TcpClient

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

问题描述

我正在编写TcpListener和TcpClient类的包装器,它们只是在端口上侦听,在建立连接时创建tcp客户端,然后从客户端接收数据。

在包装器类中,我有一个Disconnect()方法,它应该完成处理任何排队的消息,然后终止与客户端的连接。但是,每当我尝试重新连接到客户端并从中读取数据时,我每次尝试关闭客户端都会产生以下异常:

System.IO.IOException:无法从传输中读取数据连接:远程主机强行关闭exi sting连接。 ---> System.Net.Sockets
.SocketException:远程主机强制关闭现有连接
在System.Net.Sockets.Socket.Receive(Byte []缓冲区,Int32偏移量,Int32大小,
SocketFlags socketFlags)
在System.Net.Sockets.NetworkStream.Read(Byte []缓冲区,Int32偏移量,Int32 s
ize)
---内部异常堆栈跟踪结束 - - 在System.Net.Sockets.NetworkStream.Read(Byte []缓冲区,Int32偏移量,Int32 s
ize)

--------- -------------------------------------------------- ----------------------------------------

到目前为止我尝试过TcpClient.Close(),TcpClient.Client.Disconnect(false)和NetworkStream.Close(),所有这些都会产生上述行为。

如何关闭连接到客户端正确,所以我没有收到此错误,因此后续连接成功?

谢谢!

I'm writing a wrapper around the TcpListener and TcpClient classes that simply will listen on a port, create a tcp client when a connection is established, and then received data from the client.

In the wrapper class, I have a Disconnect() method that should finish processing any queued messages and then terminate the connection to the client. However, every attempt I have made to close the client produces the following exception anytime I attempt to reconnect to the client and read data from it:

System.IO.IOException: Unable to read data from the transport connection: An exi
sting connection was forcibly closed by the remote host. ---> System.Net.Sockets
.SocketException: An existing connection was forcibly closed by the remote host
   at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size,
 SocketFlags socketFlags)
   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 s
ize)
   --- End of inner exception stack trace ---
   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 s
ize)

---------------------------------------------------------------------------------------------------

So far I have tried TcpClient.Close(), TcpClient.Client.Disconnect(false), and NetworkStream.Close(), all of which produce the behavior described above.

How can I close the connection to the client properly so I do not receive this error and so subsequent connections are successful?

Thanks!

推荐答案

你好,

您可能想查看这些链接。

停止TcpListener的正确方法
TcpClient Close方法不会关闭底层TCP连接
Hello,

You might want to check these links.

Proper way to stop TcpListener
The TcpClient Close method does not close the underlying TCP connection


这篇关于如何正确关闭TcpClient的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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