如果服务器重新启动,如何将客户端套接字重新连接到我的服务器

时间:2017-07-06 23:39:53

标签: vb.net sockets tcp server client

我试图使用套接字建立客户端 - 服务器连接。

它基本上运作得很好;只有一个问题是当我在服务器计算机上关闭并重新打开我的服务器时,客户端不会重新连接

这是我的客户代码:

Imports System.Net.Sockets
Imports System.Threading
Imports System.IO
Public Class Form1
        Public Delegate Sub MessageReceivedEventHandler(ByVal sender As Object, ByVal e As MessageReceivedEventArgs)
        Public Delegate Sub ClientConnectedEventHandler(ByVal sender As Object, ByVal e As ClientConnectedEventArgs)
        Public Event MessageReceived As MessageReceivedEventHandler
        Public Event ClientConnected As ClientConnectedEventHandler
        Public Buffer As Byte()
        Public Shared Client As TcpClient
        Dim Port As Integer = 5050
    Dim host As String = "computer name"
    Dim KEY As String = "mykey"

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim T As New Thread(AddressOf run)
        T.Start()
    End Sub


    Private Sub run()
        ' Connect to the server'
        Client = New TcpClient(host, Port)
        Dim T As New Thread(AddressOf Receiver, 10) 
        T.Start()
    End Sub

    Public Shared Function StringToByte(ByVal STR As String) As Byte()
        Return System.Text.Encoding.Default.GetBytes(STR)
    End Function
    Public Shared Function ByteToString(ByVal BYS As Byte()) As String
        Return System.Text.Encoding.Default.GetString(BYS)
    End Function
    Public Sub Data(ByVal Sender As Object, ByVal Data As MessageReceivedEventArgs) Handles Me.MessageReceived
        Dim info As Byte() = Data.Message
        Dim Client As Socket = Data.clientSocket
        Dim ID As String = Data.Sender
        Dim Arr As String() = Split(System.Text.Encoding.Default.GetString(info), "mykey")
        Try
            Select Case Arr(0)

                Case "MSG"
                MsgBox(Arr(1))
                           End Select
        Catch ex As Exception
            MsgBox("Error Detected in Data Client :" & ex.Message)
        End Try
    End Sub

    Sub Receiver()
        Dim M As New MemoryStream
        Try
                If Client.Available > 0 Then
                    ReDim Buffer(Client.Available - 1)
                    Client.Client.Receive(Buffer, 0, Buffer.Length, SocketFlags.None)
                    M.Write(Buffer, 0, Buffer.Length)
                    If System.Text.Encoding.Default.GetString(M.ToArray).Contains("EOF") Then
                        Dim Data As Byte() = (M.ToArray).Remove(ConfigTcp.ENDOFPACKET)
                        Dim Msg As New MessageReceivedEventArgs
                        Msg.Message = Data
                        Msg.clientSocket = Client.Client
                        Msg.Sender = Client.Client.Handle.ToString()
                        RaiseEvent MessageReceived(Me, Msg)
                        M.Dispose()
                        M = New MemoryStream
                    End If
                End If
                Thread.Sleep(1)
        Catch ex As Exception
            MsgBox("Error Detected :" & ex.Message)
        End Try
    End Sub
    Public Shared Sub Send(ByVal sock As Socket, ByVal s As String)
            Send(sock, System.Text.Encoding.UTF8.GetBytes(s))
        End Sub
        Private Shared Sub Send(ByVal sock As Socket, ByVal b As Byte())
            Try
                Dim Memory As MemoryStream = New MemoryStream
                Dim CB As Byte() = b
                Memory.Write(CB, 0, CB.Length)
                Memory.Write(ConfigTcp.ENDOFPACKET, 0, ConfigTcp.ENDOFPACKET.Length)
                sock.Send(Memory.ToArray, 0, Memory.Length, SocketFlags.None)
                Memory.Dispose()
            Catch x As Exception
            End Try
        End Sub
    End Class
    Public Class MessageReceivedEventArgs
        Inherits EventArgs
        Public Sender As String
        Public clientSocket As Socket
        Public Message As Byte()
    End Class
    Public Class ClientConnectedEventArgs
        Inherits EventArgs
        Public clientID As String
        Public clientSocket As Socket
    End Class

2 个答案:

答案 0 :(得分:0)

您的客户需要处理断开连接并在需要时重新连接。

要实现此目的,您可以捕获SocketException并查看套接字关闭的原因。

根据例外情况,您可以运行一种方法让客户重新连接。

Public Sub DoReconnect()
    Dim SecondsToWait as Integer=1
    Do
        Try
            Client = New TcpClient(host, Port)
            Exit Do
        Catch SockEx as SocketException
            'TODO: decide whether to attempt reconnection or exit
        Catch Ex as Exception
            'TODO: Most likely should terminate the program here
            Console.WriteLine(Ex.ToString())
            Exit Do
        End Try 
        System.Threading.Thread.Sleep(SecondsToWait*1000) 
        SecondsToWait <<=1 ' Exponential Back Off Time
    Loop   
End Sub      

答案 1 :(得分:0)

@Alexander Higgins 我试过这样的东西,但似乎 SocketException 只在第一次打开服务器之前发生。如果我关闭服务器并重新打开它,它就不会捕获SocketException

   Public Sub DoReconnect()
    re:
            Thread.Sleep(1000)
            Try
                Client = New TcpClient(host, Port)
                Dim T As New Thread(AddressOf Receiver, 10)
                T.IsBackground = True
                T.Start()
            Catch SockEx As SocketException
                MsgBox("SocketException " + SockEx.Message)
                GoTo re

            Catch Ex As Exception
                MsgBox("Exception " + Ex.Message)

            End Try


        End Sub
        Private Sub run()
            DoReconnect()
        End Sub