我有一个处理 TcpClient 的类。该类应该做的是:
while the other end has not done a graceful close or we are stopping
{
receive a request
process it
send response
}
因为我不知道其他客户端何时会发送请求,所以我无法在设置超时的情况下进行读取,所以到目前为止我所拥有的是:
While Not Me.Stopping()
Try
If tcpClient.Available >= My.Settings.minimumModBusTcpFrameSize Then
processer = New MessageProcesser(Me, tcpClient)
processer.ProcessMessage()
End If
Catch ex As TimeoutException
''#Do not nothing, the current message will timeout on origin too.
End Try
End While
这种方法的问题是我永远不知道客户端何时对 Close() 进行了远程调用。
有没有办法解决这个问题?
最佳答案
我不明白为什么你不能执行超时的 Read
...如果读取超时你可以重试,而如果 Read
返回0 则连接已关闭。
编辑:是的,我已经确认了此处的行为 - 进一步阅读似乎确实失败了。这真的很奇怪...我将在这里留下我的答案,因为我认为应该是合适的 - 希望在某个时候我有时间再次调查它。
关于.net - 在 .NET 中关闭另一端时如何关闭 TcpClient?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1973956/