Question

I've done a fair amount of searching and I'm sure I'm close, but I'm having problems and hoping someone can help.

I have an ethernet barcode scanner I need to be listening to constantly. I've tried using NetworkStream.Read in a separate thread, but then found out there is a 'BeginRead' function for async network streams. Problem is I can't get it working at all.

Here's the code I've got:

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

It crashes on Dim message As String = Encoding.ASCII.GetString(buffer, 0, bytesRead) with error Array cannot be null.

Any ideas what I'm doing wrong?

Était-ce utile?

La solution

You passed stream (a NetworkStream) as the AsyncState parameter to BeginRead().
You can't cast that to a Byte() in the EndRead callback.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top