我做了相当多的搜索,我确信我很接近,但我遇到了问题并希望有人可以提供帮助。
我有一个以太网条形码扫描仪,我需要不断收听。我尝试过使用NetworkStream
。在另一个线程中读取,但后来发现异步网络流有一个“BeginRead
”函数。问题是我根本无法使用它。
这是我得到的代码:
Public Class ScannerConnect
Private client As TcpClient
Property server As String
Property port As Int32 = 2005
Private data As [Byte]()
Sub Connect()
Try
client = New TcpClient(server, port)
Catch e As ArgumentNullException
Console.WriteLine("ArgumentNullException: {0}", e)
Catch e As SocketException
Console.WriteLine("SocketException: {0}", e)
End Try
End Sub 'Connect
Sub ListenASync()
stream = client.GetStream()
data = New [Byte](256) {}
stream.BeginRead(data, 0, data.Length, AddressOf ReadASync, stream)
End Sub
Private Sub ReadASync(ar As IAsyncResult)
Dim buffer As Byte() = TryCast(ar.AsyncState, Byte())
Dim bytesRead As Integer = stream.EndRead(ar)
Dim message As String = Encoding.ASCII.GetString(buffer, 0, bytesRead)
MsgBox(message)
stream.BeginRead(buffer, 0, buffer.Length, AddressOf ReadASync, buffer)
End Sub
End Class
它崩溃了
昏暗消息为String = Encoding.ASCII.GetString(buffer, 0, bytesRead)
有错误
Array
不能是null
。
任何想法我做错了什么?
答案 0 :(得分:2)
您将stream
(NetworkStream
)作为AsyncState参数传递给BeginRead()
。
您无法将其转换为Byte()
回调中的EndRead
。