How can you reuse or reconnect to a socket on the same port after disconnecting?

I am doing a simple project involving one server program and one client program. He should check if the client is connected (from the server side) and vice versa for the client.

When a client loses the Internet, the server should know that it is disconnected. Then the client must reconnect to the server when it restores the Internet

When a client loses the Internet and then restores the Internet, I cannot reconnect to the same port.

I tried to stop listening to the server and not close the socket, and that didn't work either. I tried so many properties for sockets in terms of reuse, and also tried lingering things.

I saw that it may depend on some property TIME_WAITset by the OS in the registry (in the case of Windows). My question to repeat is to be able to use the same socket (more importantly, the same port) to reconnect after the client has lost and restored the Internet, and still listened, waiting for reconnection .

As I said, I can detect when it disconnects from the server side, as well as from the client, but when I try to reconnect using the same port and with the same socket or restartable socket, it still won’t connect, and it will not appear at all. Is there any suggestion to help solve this problem? I have been looking for this problem for a long time.

Scenario:

  • Server is listening
  • Client connects to server
  • Disconnect the client from the Internet
  • -
  • ( )

TL; DR -, .

CODE:

    private void button2_Click(object sender, EventArgs e)
    {

        // This will stop the threads/connections and toggle the button back to its original state
        if (button2.Text == "Stop Listening")
        {

            listener.Close();
            stop = true;
            threadsActive = false;
            button2.Text = "Start Listening";
            textBox1.AppendText("Manually Closed Threads/Connections" + Environment.NewLine);

        }
        else
        {

            listenThread = new Thread(listenLoop);
            listenThread.IsBackground = true;
            status = new Thread(checkIfOnline);
            status.IsBackground = true;
            stop = false;
            threadsActive = true;
            button2.Text = "Stop Listening";
            localEndPoint = new IPEndPoint(IPAddress.Parse("129.59.79.65"), 3000);
            listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            listenThread.Start();
            status.Start();

        }

    }

=============================================== =====

private void listenLoop()
    {

        try
        {

            listener.Bind(localEndPoint);
            listener.Listen(100);

            textBox1.AppendText("Waiting for a client..." + Environment.NewLine);

            listener = listener.Accept();
            textBox1.AppendText("Client Connected!!" + Environment.NewLine);

            status.Start();

            while (!close)
            {

                if (stop)
                    return;
                // server connection loop

            }

            if(close)
                return;

        }
        catch (Exception excp)
        {



        }

    }

=============================================== =====

private void ResetSocket()
    {

        // stop all threads and connections
        stop = true;
        listener.Close();

        textBox1.AppendText("Attempting to kill threads..." + Environment.NewLine);
        //while (listenThread.IsAlive == true || status.IsAlive == true) { /*loop until the threads are killed*/ textBox1.AppendText("Closing Threads..."); }
        //listener.Close();
        threadsActive = false;

        textBox1.AppendText("All Threads/Connections Closed" + Environment.NewLine + "Restarting Threads/Connections..." + Environment.NewLine);

        // re-establish and start threads and connections again
        stop = false;
        listenThread = new Thread(listenLoop);
        listenThread.IsBackground = true;
        status = new Thread(checkIfOnline);
        status.IsBackground = true;
        threadsActive = true;
        localEndPoint = new IPEndPoint(IPAddress.Parse("129.59.79.65"), 3000);
        listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        listenThread.Start();
        status.Start();

        textBox1.AppendText("Threads/Connections Restarted Successfully" + Environment.NewLine);

    }
+4
2

. .

. , , . , , .

, IMO - ( ).

TCP/IP.NET FAQ . .NET, TCP/IP.

+2

. , , . . . , , , , .

private void ListenForIncomingHttpRequests()
{
    AwaitNetworkAvailability();

    // create
    var serverSocket = 
        new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

    // bind
    var localEndpoint = new IPEndPoint(IPAddress.Any, port: 12000);
    serverSocket.Bind(localEndpoint);

    // listen
    serverSocket.Listen(backlog: 25);

    while (true)
    {
        AwaitNetworkAvailability();

        try
        {
            // client connects to the server
            using (var clientSocket = serverSocket.Accept())
            {
                ProcessServerSocketRequest(clientSocket);
            }
        }
        catch (Exception ex)
        {
            _logger.Write(ex.ToString());
        }
    }
}
0

All Articles