如何在拔下电缆后立即重新连接插座

时间:2017-05-27 02:20:40

标签: .net vb.net sockets network-programming

我有一个WPF客户端应用程序,它连接到多个嵌入式设备的服务器。每个连接都保持打开数小时或几天。服务器将定期从网络中拔出,然后重新插入网络。如果用户在拔出插头之前正常断开插座,则一切正常。但是,如果用户先拔下插头而没有断开插座,则需要多次尝试重新连接插座。每次连接尝试大约需要60秒。不得不等待一分钟或更长时间来重新建立沟通是令人讨厌的。

拔下电缆时,插座进入FIN_WAIT_1状态(通过NETSTAT观察)。我想强行关闭套接字,并在发生这种情况时更快地重新连接。如何关闭套接字以避免重新连接时出现麻烦的延迟?

命令处理循环:

    Dim _socket As TcpClient

    Private Sub ProcessCommands()
    Dim command As Byte()
    Dim response As New StringBuilder
    Dim nextByte As Integer
    Dim receiveResponse As Boolean

    Using socketStream As NetworkStream = _socket.GetStream()
        While (True)
            Try
                socketStream.WriteTimeout = SOCKET_TIMEOUT
                socketStream.ReadTimeout = SOCKET_TIMEOUT

                'grab the next message and send it over the network
                command = Encoding.ASCII.GetBytes(_commands.Take(_cancelPumpMessages.Token) + vbCr)
                socketStream.Write(command, 0, command.Length)
                socketStream.Flush()
                receiveResponse = True

                'await the response
                While (receiveResponse)
                    nextByte = socketStream.ReadByte()
                    If nextByte < 0 Then Exit While 'socket it closed
                    If nextByte = DELIMITER Then
                        'end of the message, let the listeners know
                        RaiseEvent ResponseReceived(Me, response.ToString)
                        response.Clear()
                        receiveResponse = False
                    Else
                        response.Append(Chr(nextByte))
                    End If
                End While
            Catch ex As ArgumentNullException
                Exit While
            Catch ex As ArgumentOutOfRangeException
                Exit While
            Catch ex As SocketException
                Exit While
            Catch ex As IOException
                Exit While
            Catch ex As ObjectDisposedException
                Exit While
            Catch ex As OperationCanceledException
                Exit While
            End Try
        End While
    End Using
    Disconnect()
End Sub

断开方法:

    Public Sub Disconnect() Implements IConnection.Disconnect
    If _socket IsNot Nothing Then
        StopPolling()
        Try
            If _cancelPumpMessages IsNot Nothing Then _cancelPumpMessages.Cancel()
        Catch ex As ObjectDisposedException
            'pass
        End Try
        _socket.Close()
        _socket.Dispose()
        _socket = Nothing
    End If
    Status = ConnectionState.Disconnected
End Sub

0 个答案:

没有答案