【发布时间】:2015-04-28 05:08:09
【问题描述】:
我有以下代码作为 TCP 服务器的一部分
Private Sub StartTcpClient(ByVal client As TcpClient)
Dim bytesRead As Integer
Dim RxBuffer(1024) As Byte
Dim RxDataStr As String = ""
Dim BeginTime As Date = Date.Now
Dim CurrentTime As Date
Dim ElapsedTicks As Long = -1
'Dim elapsedSpan As New TimeSpan(elapsedTicks)
While True
bytesRead = client.GetStream.Read(RxBuffer, 0, RxBuffer.Length)'What happen here?
If bytesRead > 0 Or ElapsedTicks < 3 * 10000000.0 Then 'Espera hasta 3 segundos
CurrentTime = Date.Now
ElapsedTicks = CurrentTime.Ticks - BeginTime.Ticks
'RxDataStr = System.Text.ASCIIEncoding.ASCII.GetString(RxBuffer, 0, bytesRead) 'Original
RxDataStr += System.Text.ASCIIEncoding.Default.GetString(RxBuffer, 0, bytesRead) 'UTF8
Else
client.Close()
AckString = RxDataStr
AckReady = True
AckPending = False
Exit Sub
End If
End While
End Sub
我想知道执行 GetStream.Read 行时会发生什么。 它会从我的代码中消失,并且在收集到一些数据或发生错误或其他事情之前不会回来?
如果数据到达之间的时间大于 3 秒,我需要做的是关闭当前连接。
【问题讨论】:
-
一般是的,
Stream.Read是一个阻塞读取。你可能想看看 async/await 来做异步 I/O。 -
我使用的是线程,所以我的 GUI 没有问题,但是使用这部分线程代码。如果我在上面的代码中使用 async/await 异步 I/O,While 循环不会超出处理器吗?我正在考虑将 ReceiveTimeout 更改为 3000。
标签: vb.net sockets tcplistener