我从 RFID 阅读器读取数据时遇到问题。我通过 tcp 连接到阅读器并等待 DataAvailable 为真,然后读取数据直到我得到数据字符的结尾。然后我就回去等待一个新的DataAvailable。这是在函数的自己的线程中完成的。
似乎有某种超时,如果我在几分钟内没有得到任何数据,那么它就在 do/loop 中等待 DataAvailable。我将卡放在 RFID 阅读器上,它发出哔哔声,但没有可用数据。我没有得到任何异常,并且信息说 clientsocket 仍然连接。还有什么我可以检查的吗?
如果我每隔一分钟将卡放到读卡器上,这似乎永远不会发生。所以 2-3 minutes idle:ing 似乎可以做到这一点。
这是我从套接字读取数据的代码,我删除了一些不相关的代码:
Sub test(ByVal ip As String, ByVal port As Integer)
' this sub is meant to run forever
Try
Dim clientSocket As New System.Net.Sockets.TcpClient()
clientSocket.Connect(ip, port)
Using serverStream As NetworkStream = clientSocket.GetStream()
Do 'loop forever or until error occur
'Every new dataentry starts here
Dim inStream(0) As Byte
Dim returndata As String = ""
Do 'loop forever
Do Until serverStream.DataAvailable 'loop until data exists to read
If clientSocket.Connected = False Then
'this will never happen.
'but if there are more than 5 minutes between data then
'it never got data again as if no data was sent.
Exit Sub
End If
Application.DoEvents()
Loop
'there is data to read, read first byte and
serverStream.Read(inStream, 0, 1)
If inStream(0) = 13 Then
'got end of data
'exit loop if reading chr 13.
returndata &= System.Text.Encoding.ASCII.GetString(inStream)
Exit Do
End If
Loop
GotData(returndata)
Loop
End Using
Catch ex As Exception
' handle error
Finally
'close connection if open
End Try
End Sub