vb.net我从套接字收到(无法从传输连接中读取数据)错误消息

时间:2018-10-24 04:19:30

标签: vb.net sockets

我正在尝试在客户端上使用非同步连接服务器,但是有时我在客户端上收到错误消息。我该如何解决这个问题?

如何更改为回调?

错误代码:

  

无法从连接所在的传输连接中读取数据   关闭

     

在System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)   在TFD_SoftPhone.MD_Function.ConnectionInfo.DoReadData(IAsyncResult   结果)

Public Class ConnectionInfo

    Private _AppendMethod As Action(Of String)
    Private _Client As TcpClient
    Private _Stream As NetworkStream
    Private _LastReadLength As Integer
    Private _Buffer(5120) As Byte

    Public ReadOnly Property AppendMethod As Action(Of String)
        Get
            Return _AppendMethod
        End Get
    End Property

    Public ReadOnly Property Client As TcpClient
        Get
            Return _Client
        End Get
    End Property

    Public ReadOnly Property Stream As NetworkStream
        Get
            Return _Stream
        End Get
    End Property

    Public ReadOnly Property LastReadLength As Integer
        Get
            Return _LastReadLength
        End Get
    End Property

    Public Sub New(address As IPAddress, port As Integer, append As Action(Of String))

        _AppendMethod = append
        _Client = New TcpClient
        Try
            _Client.SendTimeout = 45000
            _Client.ReceiveTimeout = 45000
            _Client.Connect(address, port)
            _Stream = _Client.GetStream
        Catch ex As Exception

            If _Client.Connected Then _Client.Close()
            If Not IsNothing(_Client) Then _Client = Nothing
            If Not IsNothing(_Stream) Then _Stream = Nothing
        End Try

    End Sub


    Public Sub AwaitData()

        Try
            If Not IsNothing(_Stream) Then
                _Stream.ReadTimeout = 45000
                _Stream.WriteTimeout = 45000
                _Stream.BeginRead(_Buffer, 0, _Buffer.Length, AddressOf DoReadData, Me)
            End If
        Catch ex As Exception

        End Try

    End Sub


    Public Sub Close()

        If _Client IsNot Nothing Then _Client.Close()
        _Client = Nothing
        _Stream = Nothing

    End Sub


    Private Sub DoReadData(result As IAsyncResult)

        Dim info As ConnectionInfo = CType(result.AsyncState, ConnectionInfo)

        Try
            If info._Stream IsNot Nothing AndAlso info._Stream.CanRead Then
                info._LastReadLength = info._Stream.EndRead(result)
                ReDim Preserve _Buffer(info._LastReadLength - 1)
                If info._LastReadLength > 0 Then
                    Dim message As String = Encoding.GetEncoding("Big5").GetString(info._Buffer)
                    info._AppendMethod(message)
                    ReDim Preserve _Buffer(5120)
                Else

                End If
                info.AwaitData()
            Else

            End If
        Catch ex As Exception
            info._LastReadLength = -1
            info._AppendMethod(ex.Message)
        End Try

    End Sub

End Class

0 个答案:

没有答案