.net socket programming error [How to Solve]

The development of a C/s project involves the problem of regular reconnection of the client after the server is stopped. During the development process, an error is reported as follows:

After the socket is disconnected, it can only be reconnected asynchronously, and can only be connected to different endpoints.   Beginconnect must be called on the thread that will not exit before the operation is completed.

After searching for relevant information on the Internet, the problem was not solved. A whim occurred and the universal list type was used to solve the problem. The methods are as follows:

Add global variables first

Private _Socket As New List(Of Socket)

Add several more in the process of connection_ Socket.Clear():

Private Sub ConnectServer()
        _Socket.Clear()
        Dim SockClient As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) 
        _Socket.Add(SockClient)
        Dim Address As IPAddress = IPAddress.Parse(_ServerIPString)
        Dim Endpoint As New IPEndPoint(Address, _ServerPort)
        Try 'Catching exceptions
            _Socket(0).Connect(Endpoint) 'initiate the connection, where the first index in the List is used instead of the local SockClient
        Catch ss As SocketException
            Dim strErrorMsg As String = ss.SocketErrorCode.ToString
            strErrorMsg = strErrorMsg.Replace("TimedOut", "Connection timeout!")
            strErrorMsg = strErrorMsg.Replace("ConnectionRefused", "Connection rejected!")
            If SockClient.Connected Then SockClient.Close()
            _Socket.Clear()
            MessageBox.Show(strErrorMsg, "Connection exception", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Return
        Catch s As Exception
            If SockClient.Connected Then SockClient.Close()
            _Socket.Clear()
            MessageBox.Show(s.Message, "exception", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Return
        End Try

End Sub

be accomplished

Test results:

After repeatedly disconnecting the server, call the connectserver process again to connect again. The connection is successful and no error is reported.

Read More: