0
    Private Sub Receiving(ByVal iAr As IAsyncResult)
    Console.WriteLine("Receiving callback started" + vbNewLine)
    Try
        SyncLock client.GetStream
            Try
                client.GetStream.EndRead(iAr)
            Catch
                Console.WriteLine("exciting")
                Exit Sub
            End Try
        End SyncLock
    Catch ex As Exception
        Console.WriteLine("exciting")
        Exit Sub
    End Try

    Dim sReader As StreamReader
    Dim nChar As Integer
    Dim StrBuffer(4096) As Char

    SyncLock client.GetStream
        sReader = New StreamReader(client.GetStream)

        Try
            nChar = sReader.Read(StrBuffer, 0, bByte.Length)
        Catch ex As Exception
            Console.WriteLine(ex)
        End Try


        Console.WriteLine(client.GetStream.CanRead)
        newStr = New String(StrBuffer, 0, nChar)

        Console.WriteLine(newStr)

        Console.WriteLine("Receiving callback callbacked" + vbNewLine)

        client.GetStream.BeginRead(bByte, 0, 4096, AddressOf Receiving, Nothing)
    End SyncLock
End Sub

这是我的代码,我已经调试了一个小时,我找不到问题,因此我找不到解决方案

应该发生的是接收方法获取一个字节数组,在调试时数组不是空的,我已经检查过了,但似乎有问题的地方是它读取的行

nChar = sReader.Read(StrBuffer, 0, bByte.Length)

在这一行,调试只是停止无事可做,如果我删除该行,功能将继续,但问题出在这一行,我真的不知道是什么原因造成的。

如果您需要更多信息,请问我,我对此感到非常困惑,谢谢

4

1 回答 1

1

执行 EndRead() 时,接收到的数据已经在您的字节数组“bByte”中。EndRead() 的返回值将是读取的字节数。您正在尝试使用 StreamReader 再次向下读取,但在此之前您已经在缓冲区中获得了数据。

我不确定你是如何编码数据的,但通常你会在接收端做更多这样的事情:

Private Sub Receiving(ByVal iAr As IAsyncResult)
    Console.WriteLine("Receiving callback started" + vbNewLine)
    Dim nChar As Integer = client.GetStream.EndRead(iAr)
    Dim newStr As String = Encoding.ASCII.GetString(bByte, 0, nChar)
    Console.WriteLine(newStr)
    Console.WriteLine("Receiving callback callbacked" + vbNewLine)
    client.GetStream.BeginRead(bByte, 0, bByte.Length, New AsyncCallback(AddressOf Receiving), Nothing)
End Sub
于 2013-11-07T05:34:27.670 回答