我已經做了大量的搜索,並且我確定我很接近,但是我遇到了問題並希望有人能夠提供幫助。閱讀異步網絡流
我有一個以太網條碼掃描器,我需要不斷地收聽。我試過使用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
。
任何想法我做錯了什麼?
如果TryCast失敗,不會'Byte'爲空/空,因爲你不檢查它,你會得到錯誤 – Plutonix