C# TCP重连客户端的正确实现
我必须编写一个能够重新连接到服务器的 TCP 客户端
。由于网络连接质量差或某些维护问题,服务器可能不可用。我正在寻找该领域的优质解决方案。
我当前的解决方案如下:
- 在 ConnectionState 枚举 {Offline、Online、Connecting} 中保持连接状态,
- 使用
TcpClient
类创建客户端。 - 创建两个名为
ConnectionCheckTimer
的计时器,和ReconnectTimer
- 连接到服务器
- 启动读取器线程,并使用 tcpClient.GetStream() 执行连接检查计时器
- 读取,然后
- 在异常发生时 从此流中读取陷入 readerLoop 的客户端状态更改为离线,并启动 ReconnectTimer
ConnectionCheckTimer
定期检查 LastMessageTimestamp 并将其与当前时间进行比较,如果间隔大于 maxValue,则启动ReconnectTimer
目前我'我对此解决方案不满意,因为它仍然会在 TcpClient.NetworkStream 上生成 ObjectDisposeException 等异常。我正在寻找一些干净且可重用的 Tcp 重新连接客户端实现,它能够处理连接、断开连接、读取数据期间可能发生的所有套接字问题。
I have to write a TCP Client
that will have ability to reconnect to server. The server can be unavailable due to poor network connection quality or some maintenance issues. I'm searching for quality solutions in this area.
My current solutions is following:
- keep connection state in ConnectionState enum {Offline, Online, Connecting}
- create client with
TcpClient
class. - create two timers called
ConnectionCheckTimer
, andReconnectTimer
- connect to server
- start reader thread and connection check timer
- reading is performed with tcpClient.GetStream() and then reading from this stream
- when Exception is caught in readerLoop client state is changed to offline and ReconnectTimer is launched
ConnectionCheckTimer
periodically checks lastMessageTimestamp and compares it with current time if the interval is greater then maxValue it launchesReconnectTimer
Currently i'm not satisfied with this solution because it still generates exceptions for instance ObjectDisposedException on TcpClient.NetworkStream. I'm looking for some clean and reusable Tcp reconnecting client implementation that is able to cope with all sockets problems that can occur during connecting, disconnecting, reading data.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您遇到连接问题,总会有例外情况。我认为你已经有了一个合理的轮廓,你只需要处理例外情况。您可以从自己的 Socket 类实现开始并编写 TCPIP 服务器。起始代码位于 MS:
http://msdn.microsoft .com/en-us/library/fx6588te(VS.71).aspx
C# 代码位于 VB 页面的中间位置。
If you have connection issues, you will always have exceptions. I think you have a sound outline, you just need to handle the exceptions. You could start with your own Socket class implemenation and write the TCPIP Server. Starter code is at MS:
http://msdn.microsoft.com/en-us/library/fx6588te(VS.71).aspx
The C# code is half way down the VB page.
您应该使用的类是“SocketAsyncEventArgs”。
我在这个项目中使用过它:
http://ts3querylib.codeplex.com/
看看AsyncTcpDispatcher 类。
The class you should use is "SocketAsyncEventArgs".
I've used it in this project:
http://ts3querylib.codeplex.com/
Have a look at the AsyncTcpDispatcher class.