断开连接后如何重新使用或重新连接到同一端口上的套接字? [英] How can you re-use or reconnect to a socket on the same port after disconnect?

查看:65
本文介绍了断开连接后如何重新使用或重新连接到同一端口上的套接字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个简单的项目,涉及一个服务器程序和一个客户端程序.它需要检查客户端是否已连接(从服务器端),反之亦然.

I am doing a simple project involving a single server program and a single client program. It needs to check if the client is connected (from the server side) and vice-versa for the client.

当客户端失去互联网连接时,服务器需要知道它已断开连接.然后,客户端需要在重新连接互联网时重新连接到服务器

When the client loses internet, the server needs to know it is disconnected. Then, the client needs to reconnect to the server when it regains internet

当客户端失去互联网,然后重新获得互联网时,我无法使用同一端口重新连接.

When the client loses internet and then regains internet, I can't reconnect using the same port.

我试图让服务器处于侦听状态,并且不关闭套接字,但这也不起作用.就重用而言,我已经尝试了许多套接字的属性,而且我也尝试了一些挥之不去的东西.

I tried leaving the server listening and not shutting the socket down and that didn't work either. I have tried so many properties for the sockets in terms of re-using and also I tried the lingering stuff too.

我已经看到它可以卡在操作系统在注册表中设置的某些 TIME_WAIT 属性上(对于Windows).我要重申的问题是,在客户端丢失并重新获得Internet之后,能够使用相同的套接字(更重要的是,使用相同的端口)重新连接,并且仍在等待重新连接.

I have seen that it can be stuck on some TIME_WAIT property set by the OS in the registry (in the case of Windows). My question, to restate, is to be able to use the same socket (more importantly the same port) to reconnect after the client lost and regained internet and to be still listening awaiting the reconnect.

就像我说的那样,我可以检测到它何时与服务器端以及客户端断开连接,但是当我尝试使用相同的端口,相同的套接字或重新启动的套接字重新连接时,它仍然无法连接,并且根本不会出现.有什么建议可以解决此问题吗?我一直在寻找解决这个问题的时间.

Like I said, I can detect when it disconnects from the server-side and also on the client but when I try to reconnect using the same port and with the same socket or a restarted socket it still won't connect and it won't show up at all. Is there any suggestion to help fix this problem? I have been searching for a long time to figure out this problem.

场景:

  1. 服务器正在监听
  2. 客户端连接到服务器
  3. 从互联网上拔出客户端
  4. 重新插入客户端Internet电缆
  5. 客户端自动重新连接到服务器(当前不在同一端口上执行此操作)

TL; DR在客户端-服务器模型上丢失并重新获得Internet,但是不能使用相同的套接字和端口连接到服务器.

TL;DR Lost and regain internet on client-server model, but can't use same socket and port to connect to server.

    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);

    }

推荐答案

不绑定客户端套接字.只有服务器端口很重要.

Don't bind the client socket. Only the server port is important.

在服务器端,仅使监听套接字保持监听状态即可.当侦听套接字接受连接时,它将返回表示该连接的 new 套接字.当您检测到连接丢失时,请关闭相应的连接插座,但使监听插座保持运行状态.

On the server side, just keep the listening socket listening. When the listening socket accepts a connection, it returns a new socket that represents that connection. When you detect a loss of connection, close the corresponding connection socket but leave the listening socket running.

另一方面,IMO检测连接中断的最佳方法是定期(双向)发送数据.

On a side note, IMO the best way to detect a loss of connection is to periodically send data (in both directions).

我有一个 TCP/IP .NET常见问题解答在我的博客上.它是.NET,但是一般概念适用于任何TCP/IP方案.

I have a TCP/IP .NET FAQ on my blog. It is .NET, but the general concepts apply to any TCP/IP scenario.

这篇关于断开连接后如何重新使用或重新连接到同一端口上的套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆