C# tcp socket keepalive I want to visit a website, but the specified time is very slow and I cannot access it

26 Views Asked by At

C# tcp socket keepalive I want to visit a website, but the specified time is very slow and I cannot access it “

I have checked the information and it is possible to use socket to maintain a connection and successfully submit a post. However, I have tried it before and it seems that it is not working because the target website can be accessed in the first 4 minutes and cannot be accessed in the last 4 minutes through regular post requests

My simple logic code

 static void Main(string[] args)
    {
        try
        {
            // 创建Socket对象
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // 设置KeepAlive参数
            byte[] keepAliveOptionValues = new byte[12];
            BitConverter.GetBytes((uint)1).CopyTo(keepAliveOptionValues, 0); // 开启Keep-Alive
            BitConverter.GetBytes((uint)30000).CopyTo(keepAliveOptionValues, 4); // 30秒开始第一次探测
            BitConverter.GetBytes((uint)5000).CopyTo(keepAliveOptionValues, 8); // 探测间隔为5秒
            socket.IOControl(IOControlCode.KeepAliveValues, keepAliveOptionValues, null);

            // 连接服务器
            socket.Connect("服务器IP地址", 8080);

            Console.WriteLine("Socket connected successfully.");

            // 创建心跳定时器,每隔一段时间发送心跳消息
            Timer heartbeatTimer = new Timer(state =>
            {
                try
                {
                    // 发送空的数据包作为心跳包
                    byte[] buffer = new byte[0];
                    socket.Send(buffer);

                    Console.WriteLine("Heartbeat sent successfully.");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error sending heartbeat: " + ex.Message);

                    // 发生异常,说明连接已经断开,尝试重新连接
                    Console.WriteLine("Attempting to reconnect...");
                    Reconnect(socket, keepAliveOptionValues);
                }
            }, null, TimeSpan.Zero, TimeSpan.FromSeconds(30)); // 每隔30秒发送一次心跳消息

            // 等待8分钟
            Thread.Sleep(8 * 60 * 1000);

            // 发送POST请求
            string postData = "{data:test}";
            string httpRequest = $"POST /test HTTP/1.1\r\n" +
                                  $"Host: yourdomain.com\r\n" +
                                  $"Content-Length: {postData.Length}\r\n" +
                                  $"Content-Type: application/json\r\n" +
                                  $"\r\n" +
                                  $"{postData}";
            byte[] requestBytes = Encoding.UTF8.GetBytes(httpRequest);
            socket.Send(requestBytes);

            Console.WriteLine("POST request sent successfully.");

            // 等待用户按下任意键退出程序
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();

            // 关闭定时器和套接字
            heartbeatTimer.Dispose();
            socket.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
        }
    }

    static void Reconnect(Socket socket, byte[] keepAliveOptionValues)
    {
        try
        {
            // 关闭现有的Socket连接
            socket.Close();

            // 创建新的Socket对象并重新连接服务器
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.IOControl(IOControlCode.KeepAliveValues, keepAliveOptionValues, null);
            socket.Connect("服务器IP地址", 8080);

            Console.WriteLine("Socket reconnected successfully.");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error reconnecting: " + ex.Message);
        }

Socket connection reuse and concurrent processing. Can I occupy the connection first if the server is blocked

node:The target server must send requests within 50 seconds and can only send 100 times

I hope to be able to post and submit successfully on time or at the specified time

0

There are 0 best solutions below