当前位置: 首页 > article >正文

GrassWebProxy

GrassWebProxy第一版:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;
using System.Net.Http;
using System.Runtime.InteropServices.ComTypes;

namespace GrassWebProxy
{
    public class Ticket
    {
        public ulong TicketNo { get; set; }
        public string BeginDateTime {  get; set; }
        public string EndDateTime { get; set; }
    }
    public class GP
    {
        public static bool CheckFlag(ref byte[] msg)
        {
            //"G" 71 0x47
            //"P" 80 0x50
            if (msg[0]==0x47 && msg[1]==0x50)
            {
                Console.WriteLine("CheckFlag OK");
                return true;
            }
            return false;
        }
        static public Ticket ReadConfig(string cfg = "Ticket1.json")
        {
            // 读取文件内容  
            string jsonContent = File.ReadAllText(cfg);

            // 反序列化JSON字符串到对象  
            Ticket ticket = JsonConvert.DeserializeObject<Ticket>(jsonContent);
            // 输出结果  
            Console.WriteLine($"{ticket.TicketNo}\r\n{ticket.BeginDateTime}---{ticket.EndDateTime}");
            return ticket;
        }
        static public bool CheckTicket(ref byte[] msg, Ticket counterfoil)
        {
            ulong ticket = (ulong)((msg[2]<< 56) | (msg[3] << 48) | (msg[4] << 40)
                | (msg[5] << 32) | (msg[6] << 24) | (msg[7] <<16)|(msg[8] <<8)|msg[9]);
            Console.WriteLine(ticket.ToString("X"));
            if(counterfoil.TicketNo==ticket)
            {
                return true;
            }
            return false;
        }
    }
    class TcpServer
    {
        private TcpListener tcpListener;
        private Thread listenThread;

        public TcpServer(string ipAddress, int port)
        {
            this.tcpListener = new TcpListener(IPAddress.Parse(ipAddress), port);
            this.listenThread = new Thread(new ThreadStart(ListenForClients));
            this.listenThread.Start();
        }

        private void ListenForClients()
        {
            this.tcpListener.Start();

            while (true)
            {
                // 阻塞直到客户端连接  
                TcpClient client = this.tcpListener.AcceptTcpClient();

                // 创建一个新的线程来处理客户端通信  
                Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
                clientThread.Start(client);
            }
        }



        /// <summary>
        /// 注意接受缓存只有4096字节。
        /// </summary>
        /// <param name="client"></param>
        private async void HandleClientComm(object client)
        {
            TcpClient tcpClient = (TcpClient)client;
            NetworkStream clientStream = tcpClient.GetStream();

            //GuestIP.RecordIpToDatabase(tcpClient);

            byte[] message = new byte[8192];
            int bytesRead;

            while (true)
            {
                bytesRead = 0;

                try
                {
                    // 阻塞直到客户端发送数据  
                    bytesRead = clientStream.Read(message, 0, message.Length);

                    if (bytesRead == 0)
                    {
                        // 客户端关闭了连接  
                        break;
                    }

                    Console.WriteLine($"Read Bytes:{bytesRead}");
                }
                catch
                {
                    // 客户端断开了连接  
                    break;
                }

                try
                {
                    //Check
                    if (GP.CheckFlag(ref message) == true && bytesRead >= 10)
                    {
                        Console.WriteLine("GrassWebProxy应用来访");

                        //Check Ticket
                        if(GP.CheckTicket(ref message,GP.ReadConfig("Ticket1.json"))==true)
                        {
                            Console.WriteLine("检票完成");

                            var data = new string(Encoding.UTF8.GetChars(message, 10, bytesRead-10));
                            Console.WriteLine(data);

                            
                            using (var httpClient = new HttpClient())
                            {
                                // 注意:这里需要处理完整的HTTP请求,包括头部和正文  
                                // 这里仅作为示例,我们实际上并没有发送整个请求  
                                var response = await httpClient.GetAsync(data);

                                var responseContent = await response.Content.ReadAsStringAsync();
                                Console.WriteLine(responseContent);
                                // 将响应写回客户端  
                                var responseBytes = Encoding.UTF8.GetBytes(responseContent);
                                await clientStream.WriteAsync(responseBytes, 0, responseBytes.Length);
                                Console.WriteLine("Send {0} Bytes.", responseBytes.Length);
                            }

                        }
                        goto End;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"{ex.Message}");
                }

                // 将接收到的数据回显给客户端  
                ASCIIEncoding encoder = new ASCIIEncoding();
                string messageString = encoder.GetString(message, 0, bytesRead);
                Console.WriteLine("Received from client: " + messageString);

                byte[] buffer = encoder.GetBytes(messageString);

                // 发送回显数据给客户端  
                clientStream.Write(buffer, 0, buffer.Length);
                clientStream.Flush();
            End:
                //    //查看来访IP信息
                //    GuestIP.ReadLastGuestIP();
                ;
            }

            tcpClient.Close();
        }
    }
    internal class Program
    {
        static void Main(string[] args)
        {
            const int port = 8422;
            TcpServer server = new TcpServer("127.0.0.1", port);

            Console.WriteLine($"TCP Server listening on port {port}...");

            // 阻止主线程结束,直到用户手动停止  
            Console.ReadLine();
        }
    }
}
Ticket1.json 文件内容:
{
  "TicketNo":1,
  "BeginDateTime": "20240728T20:30:30",
  "EndDateTime": "20240731T20:30:30"
}

GrassWebProxyV2:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;
using System.Net;
using System.Net.Http;

namespace GrassWebProxyV2
{

    public class Ticket
    {
        public ulong TicketNo { get; set; }
        public string BeginDateTime { get; set; }
        public string EndDateTime { get; set; }
    }
    public class GP
    {
        public static bool CheckFlag(ref byte[] msg)
        {
            //"G" 71 0x47
            //"P" 80 0x50
            if (msg[0] == 0x47 && msg[1] == 0x50)
            {
                Console.WriteLine("CheckFlag OK");
                return true;
            }
            return false;
        }
        static public Ticket ReadConfig(string cfg = "Ticket1.json")
        {
            // 读取文件内容  
            string jsonContent = File.ReadAllText(cfg);

            // 反序列化JSON字符串到对象  
            Ticket ticket = JsonConvert.DeserializeObject<Ticket>(jsonContent);
            // 输出结果  
            Console.WriteLine($"{ticket.TicketNo}\r\n{ticket.BeginDateTime}---{ticket.EndDateTime}");
            return ticket;
        }
        static public bool CheckTicket(ref byte[] msg, Ticket counterfoil)
        {
            /*ulong ticket = (ulong)((msg[2] << 56) | (msg[3] << 48) | (msg[4] << 40)
                | (msg[5] << 32) | (msg[6] << 24) | (msg[7] << 16) | (msg[8] << 8) | msg[9]);*/
            ulong ticket = BitConverter.ToUInt64(msg, 2); // 从索引2开始读取8个字节
            //Console.WriteLine(ticket.ToString("X"));
            if (counterfoil.TicketNo == ticket)
            {
                return true;
            }
            return false;
        }
        static public bool CheckFlagAdTicket(ref byte[] msg, Ticket counterfoil)
        {
            //"G" 71 0x47
            //"P" 80 0x50
            ulong ticket = BitConverter.ToUInt64(msg, 2); // 从索引2开始读取8个字节
            if (msg[0] == 0x47 && msg[1] == 0x50 && counterfoil.TicketNo == ticket)
            {
                return true;
            }
            return false;
        }
    }

    class SimpleWebProxy
    {
        private HttpListener listener;

        public SimpleWebProxy(int port)
        {
            // 初始化HttpListener,监听所有传入HTTP请求  
            listener = new HttpListener();
            listener.Prefixes.Add($"http://+:{port}/");
            listener.Start();

            Console.WriteLine($"Grass Web proxy listening on port {port}...");

            // 开始异步处理请求  
            Task.Run(() => ListenForRequests());
        }

        private async Task ListenForRequests()
        {
            while (true)
            {
                // 等待并获取下一个客户端连接  
                HttpListenerContext context = await listener.GetContextAsync();
                HttpListenerRequest request = context.Request;

                 假设Ticket存储在HTTP头中,名为"X-Proxy-Ticket"  
                string ticketHeader = request.Headers["X-Proxy-Ticket"];
                // 假设您有一个方法CheckTicket(string ticket)来验证ticket  
                // return CheckTicket(ticketHeader); // 这里应该是您的验证逻辑  
                // 为了示例,我们直接返回true或false(这里总是返回false以模拟验证失败)
                // 使用UTF8编码将字符串转换为byte[]  
                byte[] ticketBytes = Encoding.UTF8.GetBytes(ticketHeader);

                var counterfoil = GP.ReadConfig("Ticket1.json");
                if(GP.CheckFlagAdTicket(ref ticketBytes, counterfoil)==true)
                {
                    // 获取请求的URL(不包含查询字符串)  
                    string url = request.Url.Scheme + "://" + request.Url.Host + ":" + request.Url.Port + request.Url.AbsolutePath;
                    Console.WriteLine(url);
                    // 创建一个WebRequest到目标URL  
                    HttpWebRequest proxyRequest = (HttpWebRequest)WebRequest.Create(url);

                    // 复制请求方法(如GET、POST)  
                    proxyRequest.Method = request.HttpMethod;

                    // 如果需要,可以添加更多的请求头(这里未添加)  

                    // 发送请求到目标服务器并获取响应  
                    using (HttpWebResponse proxyResponse = (HttpWebResponse)await proxyRequest.GetResponseAsync())
                    {
                        // 将响应转发给客户端  
                        using (Stream responseStream = proxyResponse.GetResponseStream())
                        using (Stream outputStream = context.Response.OutputStream)
                        {
                            // 设置响应的HTTP状态码和状态描述  
                            context.Response.StatusCode = (int)proxyResponse.StatusCode;
                            context.Response.StatusDescription = proxyResponse.StatusDescription;

                            // 遍历所有响应头并复制到响应中  
                            foreach (string headerKey in proxyResponse.Headers.AllKeys)
                            {
                                if (headerKey != "Transfer-Encoding" &&
                                    !(context.Response.Headers.AllKeys.Contains(headerKey)))
                                {
                                    context.Response.AddHeader(headerKey, proxyResponse.Headers[headerKey]);
                                }
                            }

                            // 读取响应流并将其写入客户端的输出流  
                            byte[] buffer = new byte[4096];
                            int bytesRead;
                            while ((bytesRead = await responseStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                            {
                                await outputStream.WriteAsync(buffer, 0, bytesRead);
                            }
                        }
                    }
                }
                else
                {
                    // 票据验证失败,可以发送错误响应给客户端  
                    context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    context.Response.Close();
                }
            }
        }
    }
    internal class Program
    {
        static void Main(string[] args)
        {
            new SimpleWebProxy(8422);

            // 防止主线程退出  
            Console.WriteLine("Press Enter to exit...");
            Console.ReadLine();
        }
    }
}

GrassWebProxyV4:

// See https://aka.ms/new-console-template for more information
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Net.Http;
using System.Runtime.InteropServices.ComTypes;
using System.IO.Compression;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Runtime.Serialization;

namespace GrassWebProxy
{
    public class CustomDateTimeConverter : IsoDateTimeConverter
    {
        public CustomDateTimeConverter()
        {
            DateTimeFormat = "yyyyMMdd'T'HH:mm:ss";
        }
    }
    public class Ticket
    {
        public ulong TicketNo { get; set; }

        [JsonConverter(typeof(CustomDateTimeConverter))]
        public DateTime BeginDateTime { get; set; }

        [JsonConverter(typeof(CustomDateTimeConverter))]
        public DateTime EndDateTime { get; set; }
    }
    public class GP
    {
        public static bool CheckFlag(ref byte[] msg)
        {
            //"G" 71 0x47
            //"P" 80 0x50
            if (msg[0] == 0x47 && msg[1] == 0x50)
            {
                Console.WriteLine("CheckFlag OK");
                return true;
            }
            return false;
        }
        static public Ticket ReadConfig(string cfg = "Ticket1.json")
        {
            // 读取文件内容  
            string jsonContent = File.ReadAllText(cfg);

            // 反序列化JSON字符串到对象  
            Ticket ticket = JsonConvert.DeserializeObject<Ticket>(jsonContent);
            // 输出结果  
            Console.WriteLine($"{ticket.TicketNo}\r\n{ticket.BeginDateTime}---{ticket.EndDateTime}");
            return ticket;
        }
        static public bool CheckTicket(ref byte[] msg, Ticket counterfoil)
        {
            ulong ticket = (ulong)((msg[2] << 56) | (msg[3] << 48) | (msg[4] << 40)
                | (msg[5] << 32) | (msg[6] << 24) | (msg[7] << 16) | (msg[8] << 8) | msg[9]);
            Console.WriteLine(ticket.ToString("X"));
            if (counterfoil.TicketNo == ticket)
            {
                return true;
            }
            return false;
        }

        public static byte[] Compress(byte[] input)
        {
            using (var memoryStream = new MemoryStream())
            {
                using (var gzipStream = new GZipStream(memoryStream, CompressionMode.Compress, true))
                {
                    gzipStream.Write(input, 0, input.Length);
                }

                // 确保所有数据都被写入并压缩  
                return memoryStream.ToArray();
            }
        }
        public static byte[] DecompressGzip(byte[] gzip, int prebytes = 4096)
        {
            using (var ms = new MemoryStream(gzip))
            {
                using (var gzipStream = new GZipStream(ms, CompressionMode.Decompress))
                {
                    var buffer = new byte[prebytes];
                    using (var memoryStreamOut = new MemoryStream())
                    {
                        int read;
                        while ((read = gzipStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            memoryStreamOut.Write(buffer, 0, read);
                        }
                        return memoryStreamOut.ToArray();
                    }
                }
            }
        }
    }
    class TcpServer
    {
        private TcpListener tcpListener;
        private Thread listenThread;

        public TcpServer(string ipAddress, int port)
        {
            this.tcpListener = new TcpListener(IPAddress.Parse(ipAddress), port);
            this.listenThread = new Thread(new ThreadStart(ListenForClients));
            this.listenThread.Start();
        }

        private void ListenForClients()
        {
            this.tcpListener.Start();

            while (true)
            {
                // 阻塞直到客户端连接  
                TcpClient client = this.tcpListener.AcceptTcpClient();

                // 创建一个新的线程来处理客户端通信  
                Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
                clientThread.Start(client);
            }
        }



        /// <summary>
        /// 注意接受缓存只有4096字节。
        /// </summary>
        /// <param name="client"></param>
        private async void HandleClientComm(object client)
        {
            TcpClient tcpClient = (TcpClient)client;
            NetworkStream clientStream = tcpClient.GetStream();

            //GuestIP.RecordIpToDatabase(tcpClient);

            byte[] message = new byte[8192];
            int bytesRead;

            while (true)
            {
                bytesRead = 0;

                try
                {
                    // 阻塞直到客户端发送数据  
                    bytesRead = clientStream.Read(message, 0, message.Length);

                    if (bytesRead == 0)
                    {
                        // 客户端关闭了连接  
                        break;
                    }

                    Console.WriteLine($"Read Bytes:{bytesRead}");
                }
                catch
                {
                    // 客户端断开了连接  
                    break;
                }

                try
                {
                    //Check
                    if (GP.CheckFlag(ref message) == true && bytesRead >= 10)
                    {
                        Console.WriteLine("GrassWebProxy应用来访");
                        //Check Ticket
                        if (GP.CheckTicket(ref message, GP.ReadConfig("Ticket1.json")) == true)
                        {
                            Console.WriteLine("检票完成");

                            var data = new string(Encoding.UTF8.GetChars(message, 10, bytesRead - 10));
                            Console.WriteLine(data);


                            using (var httpClient = new HttpClient())
                            {
                                // 注意:这里需要处理完整的HTTP请求,包括头部和正文  
                                // 这里仅作为示例,我们实际上并没有发送整个请求  
                                var response = await httpClient.GetAsync(data);

                                var responseContent = await response.Content.ReadAsStringAsync();
                                Console.WriteLine(responseContent);
                                // 将响应写回客户端  
                                //var responseBytes = Encoding.UTF8.GetBytes(responseContent);
                                var rsbuf = await response.Content.ReadAsByteArrayAsync();
                                Console.WriteLine(rsbuf.Length);
                                var gzipbuf = GP.Compress(rsbuf);
                                Console.WriteLine(gzipbuf.Length);
                                await clientStream.WriteAsync(gzipbuf, 0, gzipbuf.Length);
                                Console.WriteLine("Send {0} Bytes.", gzipbuf.Length);
                                clientStream.Flush();
                                Console.WriteLine("END");
                                tcpClient.Close();
                            }

                        }
                        goto End;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"{ex.Message}");
                }

                // 将接收到的数据回显给客户端  
                ASCIIEncoding encoder = new ASCIIEncoding();
                string messageString = encoder.GetString(message, 0, bytesRead);
                Console.WriteLine("Received from client: " + messageString);

                byte[] buffer = encoder.GetBytes(messageString);

                // 发送回显数据给客户端  
                clientStream.Write(buffer, 0, buffer.Length);
                clientStream.Flush();
                Console.WriteLine("END");
                tcpClient.Close();
            End:
                //    //查看来访IP信息
                //    GuestIP.ReadLastGuestIP();
                ;
            }
            
        }
    }
    internal class Program
    {
        static void Main(string[] args)
        {
            const int port = 8422;
            TcpServer server = new TcpServer("127.0.0.1", port);

            Console.WriteLine($"TCP Server listening on port {port}...");

            // 阻止主线程结束,直到用户手动停止  
            Console.ReadLine();
        }
    }
}

GrassWebProxyClient:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net;
using System.Net.Sockets;

namespace GrassWebProxyClient
{
    public class IPport
    {
        public string IP { get; set; }
        public int Port { get; set; }
    }
    public class Ticket
    {
        public ulong TicketNo { get; set; }
        public string BeginDateTime { get; set; }
        public string EndDateTime { get; set; }
    }
    internal class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string jsonFilePath = "ipport.json"; // 替换为你的JSON文件路径  

                // 读取文件内容  
                string jsonContent = File.ReadAllText(jsonFilePath);

                // 反序列化JSON字符串到对象  
                IPport ipaddr = JsonConvert.DeserializeObject<IPport>(jsonContent);

                // 输出结果  
                Console.WriteLine($"{ipaddr.IP}:{ipaddr.Port}");

                // 创建一个TcpClient实例并连接到服务器  
                TcpClient client = new TcpClient($"{ipaddr.IP}", ipaddr.Port);

                // 获取一个NetworkStream对象以进行读写  
                NetworkStream stream = client.GetStream();

                jsonFilePath = "Ticket1.json";
                // 读取文件内容  
                jsonContent = File.ReadAllText(jsonFilePath);
                // 反序列化JSON字符串到对象  
                Ticket ticket = JsonConvert.DeserializeObject<Ticket>(jsonContent);

                // 输出结果  
                Console.WriteLine($"{ticket.TicketNo}\r\n{ticket.BeginDateTime}---{ticket.EndDateTime}");
                //组装
                byte[] data = { 0x47, 0x50, 0x01, 0xF2, 0x00, 0x00, 0x00, 0x01,0x01,0x01 };
                for (int i=2,j=7;i<data.Length;i++,j--)
                {
                    data[i] = (byte)(ticket.TicketNo>>(j*8));
                    //Console.WriteLine(data[i]);
                }
                // 发送消息到服务器  
                stream.Write(data, 0, data.Length);

                // 发送消息到服务器
                // 将消息转换为字节数组  
                string message = "http://www.cjors.cn/";
                byte[] requestdata = Encoding.UTF8.GetBytes(message);
                // 将 data 和 requestdata 合并到 buffer 中  
                byte[] buffer = new byte[data.Length + requestdata.Length];
                Buffer.BlockCopy(data, 0, buffer, 0, data.Length);
                Buffer.BlockCopy(requestdata, 0, buffer, data.Length, requestdata.Length);
                stream.Write(requestdata, 0, requestdata.Length);

                // 读取服务器的响应  
                byte[] buf = new byte[8192];
                int bytesRead = stream.Read(buf, 0, buf.Length);

                // 将接收到的字节转换为字符串  
                string responseData = Encoding.UTF8.GetString(buf, 0, bytesRead);
                Console.WriteLine("Received from server: " + responseData);
                Console.WriteLine("ReceivedBytes:{0}", bytesRead);

                //将Json写入文件
                File.WriteAllText("response.html", responseData);

                // 关闭连接  
                client.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.Message);
            }

            // 等待用户按键,以便在控制台中查看结果  
            Console.WriteLine("Press Enter to continue...");
            Console.ReadLine();
        }
    }
}

GrassWebProxyClientV2:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using System.Net.Sockets;
using Newtonsoft.Json;
using System.Security.Policy;

namespace GrassWebProxyClientV2
{
    public class IPport
    {
        public string IP { get; set; }
        public int Port { get; set; }
    }
    public class CpolarInfo
    {
        public int total { get; set; }
        public item[] items { get; set; }
    }
    public class item
    {
        public string name { get; set; }
        public string create_datetime { get; set; }
        public string pubulic_url { get; set; }
    }
    public class Ticket
    {
        public ulong TicketNo { get; set; }
        public string BeginDateTime { get; set; }
        public string EndDateTime { get; set; }
    }
    internal class Program
    {
        static void GetCploarInfo()
        {
            try
            {
                string jsonFilePath = "ipport.json"; // 替换为你的JSON文件路径  

                // 读取文件内容  
                string jsonContent = File.ReadAllText(jsonFilePath);

                // 反序列化JSON字符串到对象  
                IPport ipaddr = JsonConvert.DeserializeObject<IPport>(jsonContent);

                // 输出结果  
                Console.WriteLine($"{ipaddr.IP}:{ipaddr.Port}");

                // 创建一个TcpClient实例并连接到服务器  
                TcpClient client = new TcpClient($"{ipaddr.IP}", ipaddr.Port);

                // 获取一个NetworkStream对象以进行读写  
                NetworkStream stream = client.GetStream();

                // 将消息转换为字节数组  
                //string message = "Hello from the client!";
                //byte[] data = Encoding.ASCII.GetBytes(message);
                byte[] data = { 0x4E, 0x74, 0x01, 0xF2, 0x00, 0x00, 0x00, 0x01 };

                // 发送消息到服务器  
                stream.Write(data, 0, data.Length);

                // 读取服务器的响应  
                byte[] buffer = new byte[4096];
                int bytesRead = stream.Read(buffer, 0, buffer.Length);

                // 将接收到的字节转换为字符串  
                string responseData = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                Console.WriteLine("Received from server: " + responseData);
                Console.WriteLine("ReceivedBytes:{0}", bytesRead);
                // 关闭连接  
                client.Close();
                //将Json写入文件
                File.WriteAllText("cpolarinfo.json", responseData);


            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.Message);
            }
        }
        static void UseWebProxy(string webProxyUrl,string ip,int port)
        {
            try
            {
                // 创建一个TcpClient实例并连接到服务器  
                TcpClient client = new TcpClient(ip, port);

                // 获取一个NetworkStream对象以进行读写  
                NetworkStream stream = client.GetStream();

                string jsonFilePath = "Ticket1.json";
                // 读取文件内容  
                string jsonContent = File.ReadAllText(jsonFilePath);
                // 反序列化JSON字符串到对象  
                Ticket ticket = JsonConvert.DeserializeObject<Ticket>(jsonContent);

                // 输出结果  
                Console.WriteLine($"{ticket.TicketNo}\r\n{ticket.BeginDateTime}---{ticket.EndDateTime}");
                //组装
                byte[] data = { 0x47, 0x50, 0x01, 0xF2, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01 };
                for (int i = 2, j = 7; i < data.Length; i++, j--)
                {
                    data[i] = (byte)(ticket.TicketNo >> (j * 8));
                    //Console.WriteLine(data[i]);
                }
                
                // 将消息转换为字节数组  
                // 将 data 和 requestdata 合并到 buffer 中  
                byte[] requestdata = Encoding.UTF8.GetBytes(webProxyUrl);
                byte[] buf = new byte[data.Length + requestdata.Length];
                Buffer.BlockCopy(data, 0, buf, 0, data.Length);
                Buffer.BlockCopy(requestdata, 0, buf, data.Length, requestdata.Length);

                // 发送消息到服务器
                stream.Write(buf, 0, buf.Length);

                // 读取服务器的响应  
                byte[] buffer = new byte[81920];
                //int bytesRead = stream.Read(buffer, 0, buffer.Length);
                int totalBytesRead = 0;
                int bytesRead = 0;
                string responseData = string.Empty;

                while ((bytesRead = stream.Read(buffer, totalBytesRead, buffer.Length - totalBytesRead)) > 0)
                {
                    // 将接收到的字节转换为字符串  
                    responseData = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                    Console.WriteLine("Received from server: " + responseData);
                    Console.WriteLine("ReceivedBytes:{0}", bytesRead);
                    totalBytesRead += bytesRead;
                    // 可以在这里处理已经读取的数据(例如,写入文件或进行其他处理)  
                    // 但请注意,如果处理逻辑复杂,最好先将数据复制到另一个缓冲区中  
                }

                // 现在 totalBytesRead 包含了从流中读取的总字节数
                Console.WriteLine("TotalReceivedBytes:{0}", totalBytesRead);
                //将Json写入文件
                File.WriteAllText("response.html", responseData);

                // 关闭连接  
                client.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.Message);
            }
}
        static void Main(string[] args)
        {
            Console.WriteLine("请求Cploar动态域名和端口信息......");
            GetCploarInfo();
            string jsonContent=File.ReadAllText("cpolarinfo.json");
            Console.WriteLine(jsonContent);
            CpolarInfo cpinfo = JsonConvert.DeserializeObject<CpolarInfo>(jsonContent);
            Console.WriteLine($"{cpinfo.total}");
            for (int i = 0;i<cpinfo.total;i++)
            {
                Console.WriteLine($"{cpinfo.items[i].name}\r\n{cpinfo.items[i].create_datetime}\r\n{cpinfo.items[i].pubulic_url}");
            }
            string host = string.Empty;
            for (int i = 0; i < cpinfo.total; i++)
            {
                if (cpinfo.items[i].name== "GrassWebProxy")
                {
                    host = cpinfo.items[i].pubulic_url;
                }
            }
            Console.WriteLine(host);
            // 使用Uri类来解析URL(这是更推荐的方法,因为它更健壮且能处理各种URL格式)  
            Uri uri = new Uri(host);

            // 直接从Uri对象中获取主机名  
            string hostname = uri.Host;
            int port = uri.Port;
            Console.WriteLine($"{hostname}:{port}"); // 输出: cpolard.26.tcp.cpolar.top  
            UseWebProxy("https://www.speedtest.net/", hostname, port);
        }
    }
}

GrassWebProxyClientV3:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;

namespace GrassWebProxyV3
{
    public class IPport
    {
        public string IP { get; set; }
        public int Port { get; set; }
    }
    public class CpolarInfo
    {
        public int total { get; set; }
        public item[] items { get; set; }
    }
    public class item
    {
        public string name { get; set; }
        public string create_datetime { get; set; }
        public string pubulic_url { get; set; }
    }
    public class Ticket
    {
        public ulong TicketNo { get; set; }
        public string BeginDateTime { get; set; }
        public string EndDateTime { get; set; }
    }
    internal class Program
    {
        static string GetCploarInfo()
        {
            try
            {
                string jsonFilePath = "ipport.json"; // 替换为你的JSON文件路径  

                // 读取文件内容  
                string jsonContent = File.ReadAllText(jsonFilePath);

                // 反序列化JSON字符串到对象  
                IPport ipaddr = JsonConvert.DeserializeObject<IPport>(jsonContent);

                // 输出结果  
                Console.WriteLine($"{ipaddr.IP}:{ipaddr.Port}");

                // 创建一个TcpClient实例并连接到服务器  
                TcpClient client = new TcpClient($"{ipaddr.IP}", ipaddr.Port);

                // 获取一个NetworkStream对象以进行读写  
                NetworkStream stream = client.GetStream();

                // 将消息转换为字节数组  
                //string message = "Hello from the client!";
                //byte[] data = Encoding.ASCII.GetBytes(message);
                byte[] data = { 0x4E, 0x74, 0x01, 0xF2, 0x00, 0x00, 0x00, 0x01 };

                // 发送消息到服务器  
                stream.Write(data, 0, data.Length);

                // 读取服务器的响应  
                byte[] buffer = new byte[4096];
                int bytesRead = stream.Read(buffer, 0, buffer.Length);

                // 将接收到的字节转换为字符串  
                string responseData = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                Console.WriteLine("Received from server: " + responseData);
                Console.WriteLine("ReceivedBytes:{0}", bytesRead);
                // 关闭连接  
                client.Close();
                //将Json写入文件
                File.WriteAllText("cpolarinfo.json", responseData);

                return responseData;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.Message);
            }
            return string.Empty;
        }
        static void UseWebProxy(string webProxyUrl, string ip, int port)
        {
            try
            {
                string jsonFilePath = "Ticket1.json";
                // 读取文件内容  
                string jsonContent = File.ReadAllText(jsonFilePath);
                // 反序列化JSON字符串到对象  
                Ticket ticket = JsonConvert.DeserializeObject<Ticket>(jsonContent);

                // 输出结果  
                Console.WriteLine($"{ticket.TicketNo}\r\n{ticket.BeginDateTime}---{ticket.EndDateTime}");
                //组装
                byte[] data = { 0x47, 0x50, 0x01, 0xF2, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01 };
                for (int i = 2, j = 7; i < data.Length; i++, j--)
                {
                    data[i] = (byte)(ticket.TicketNo >> (j * 8));
                    //Console.WriteLine(data[i]);
                }

                // 将消息转换为字节数组  
                // 将 data 和 requestdata 合并到 buffer 中  
                byte[] requestdata = Encoding.UTF8.GetBytes(webProxyUrl);
                byte[] buf = new byte[data.Length + requestdata.Length];
                Buffer.BlockCopy(data, 0, buf, 0, data.Length);
                Buffer.BlockCopy(requestdata, 0, buf, data.Length, requestdata.Length);
                
                // 创建一个TcpClient实例并连接到服务器  
                TcpClient client = new TcpClient(ip, port);

                // 获取一个NetworkStream对象以进行读写  
                NetworkStream stream = client.GetStream();
                // 发送消息到服务器
                stream.Write(buf, 0, buf.Length);

                // 读取服务器的响应  
                byte[] buffer = new byte[81920];
                //int bytesRead = stream.Read(buffer, 0, buffer.Length);
                int totalBytesRead = 0;
                int bytesRead = 0;
                string responseData = string.Empty;

                while ((bytesRead = stream.Read(buffer, totalBytesRead, buffer.Length - totalBytesRead)) > 0)
                {
                    // 将接收到的字节转换为字符串  
                    responseData = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                    Console.WriteLine("Received from server: " + responseData);
                    Console.WriteLine("ReceivedBytes:{0}", bytesRead);
                    totalBytesRead += bytesRead;
                    // 可以在这里处理已经读取的数据(例如,写入文件或进行其他处理)  
                    // 但请注意,如果处理逻辑复杂,最好先将数据复制到另一个缓冲区中  
                }

                // 现在 totalBytesRead 包含了从流中读取的总字节数
                Console.WriteLine("TotalReceivedBytes:{0}", totalBytesRead);

                // 关闭连接  
                client.Close();

                //将Json写入文件
                File.WriteAllText("response.html", responseData);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.Message);
            }
        }
        static void Main(string[] args)
        {
            Console.WriteLine("请求Cploar动态域名和端口信息......");
            string jsonContent = GetCploarInfo();
            CpolarInfo cpinfo = new CpolarInfo();
            if (jsonContent==string.Empty)
            {
                jsonContent = File.ReadAllText("cpolarinfo.json");
            }
            else
            {
                //
                Console.WriteLine(jsonContent);
                cpinfo = JsonConvert.DeserializeObject<CpolarInfo>(jsonContent);
                Console.WriteLine($"{cpinfo.total}");
                for (int i = 0; i < cpinfo.total; i++)
                {
                    Console.WriteLine($"{cpinfo.items[i].name}\r\n{cpinfo.items[i].create_datetime}\r\n{cpinfo.items[i].pubulic_url}");
                }
            }

            string host = string.Empty;
            for (int i = 0; i < cpinfo.total; i++)
            {
                if (cpinfo.items[i].name == "GrassWebProxy")
                {
                    host = cpinfo.items[i].pubulic_url;
                }
            }
            Console.WriteLine(host);
            // 使用Uri类来解析URL(这是更推荐的方法,因为它更健壮且能处理各种URL格式)  
            Uri uri = new Uri(host);

            // 直接从Uri对象中获取主机名  
            string hostname = uri.Host;
            int port = uri.Port;
            Console.WriteLine($"{hostname}:{port}"); // 输出: cpolard.26.tcp.cpolar.top  
            UseWebProxy("https://www.speedtest.net/", hostname, port);
            //UseWebProxy("https://29bf2803.r15.cpolar.top/html/Welcome.html", hostname, port);
        }
    }
}

GrassWebProxyClientV4:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Policy;
using System.Net;
using System.Net.Sockets;

namespace GrassWebProxyClientV4
{
    public class IPport
    {
        public string IP { get; set; }
        public int Port { get; set; }
    }
    public class CpolarInfo
    {
        public int total { get; set; }
        public item[] items { get; set; }
    }
    public class item
    {
        public string name { get; set; }
        public string create_datetime { get; set; }
        public string pubulic_url { get; set; }
    }
    public class Ticket
    {
        public ulong TicketNo { get; set; }
        public string BeginDateTime { get; set; }
        public string EndDateTime { get; set; }
    }
    public class GP
    {
        public static bool CheckFlag(ref byte[] msg)
        {
            //"G" 71 0x47
            //"P" 80 0x50
            if (msg[0] == 0x47 && msg[1] == 0x50)
            {
                Console.WriteLine("CheckFlag OK");
                return true;
            }
            return false;
        }
        static public Ticket ReadConfig(string cfg = "Ticket1.json")
        {
            // 读取文件内容  
            string jsonContent = File.ReadAllText(cfg);

            // 反序列化JSON字符串到对象  
            Ticket ticket = JsonConvert.DeserializeObject<Ticket>(jsonContent);
            // 输出结果  
            Console.WriteLine($"{ticket.TicketNo}\r\n{ticket.BeginDateTime}---{ticket.EndDateTime}");
            return ticket;
        }
        static public bool CheckTicket(ref byte[] msg, Ticket counterfoil)
        {
            /*ulong ticket = (ulong)((msg[2] << 56) | (msg[3] << 48) | (msg[4] << 40)
                | (msg[5] << 32) | (msg[6] << 24) | (msg[7] << 16) | (msg[8] << 8) | msg[9]);*/
            ulong ticket = BitConverter.ToUInt64(msg, 2); // 从索引2开始读取8个字节
            //Console.WriteLine(ticket.ToString("X"));
            if (counterfoil.TicketNo == ticket)
            {
                return true;
            }
            return false;
        }
        static public bool CheckFlagAdTicket(ref byte[] msg, Ticket counterfoil)
        {
            //"G" 71 0x47
            //"P" 80 0x50
            ulong ticket = BitConverter.ToUInt64(msg, 2); // 从索引2开始读取8个字节
            if (msg[0] == 0x47 && msg[1] == 0x50 && counterfoil.TicketNo == ticket)
            {
                return true;
            }
            return false;
        }
    }

    public class DynamicCploar
    {
        public static Uri GetGrassWebProxyHost(string notifyServer = "ipport.json")
        {
            try
            {
                string jsonFilePath = "ipport.json"; // 替换为你的JSON文件路径  

                // 读取文件内容  
                string jsonContent = File.ReadAllText(jsonFilePath);

                // 反序列化JSON字符串到对象  
                IPport ipaddr = JsonConvert.DeserializeObject<IPport>(jsonContent);

                // 输出结果  
                Console.WriteLine($"Notify Server: {ipaddr.IP}:{ipaddr.Port}");

                // 创建一个TcpClient实例并连接到服务器  
                TcpClient client = new TcpClient($"{ipaddr.IP}", ipaddr.Port);

                // 获取一个NetworkStream对象以进行读写  
                NetworkStream stream = client.GetStream();

                // 将消息转换为字节数组  
                //string message = "Hello from the client!";
                //byte[] data = Encoding.ASCII.GetBytes(message);
                byte[] data = { 0x4E, 0x74, 0x01, 0xF2, 0x00, 0x00, 0x00, 0x01 };

                // 发送消息到服务器  
                stream.Write(data, 0, data.Length);

                // 读取服务器的响应  
                byte[] buffer = new byte[1024];
                int bytesRead = stream.Read(buffer, 0, buffer.Length);

                // 将接收到的字节转换为字符串  
                string responseData = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                //Console.WriteLine("Received from server: " + responseData);
                //Console.WriteLine("ReceivedBytes:{0}", bytesRead);
                // 关闭连接  
                client.Close();
                //将Json写入文件
                File.WriteAllText("cpolarinfo.json", responseData);

                CpolarInfo cpinfo = new CpolarInfo();
                if (responseData == string.Empty)
                {
                    responseData = File.ReadAllText("cpolarinfo.json");
                }
                else
                {
                    //
                    Console.WriteLine(responseData);
                    cpinfo = JsonConvert.DeserializeObject<CpolarInfo>(responseData);
                    //Console.WriteLine($"{cpinfo.total}");
                    //for (int i = 0; i < cpinfo.total; i++)
                    //{
                    //    Console.WriteLine($"{cpinfo.items[i].name}\r\n{cpinfo.items[i].create_datetime}\r\n{cpinfo.items[i].pubulic_url}");
                    //}
                }

                string host = string.Empty;
                for (int i = 0; i < cpinfo.total; i++)
                {
                    if (cpinfo.items[i].name == "GrassWebProxy")
                    {
                        host = cpinfo.items[i].pubulic_url;
                    }
                }
                Console.WriteLine(host);
                // 使用Uri类来解析URL(这是更推荐的方法,因为它更健壮且能处理各种URL格式)  
                Uri uri = new Uri(host);

                return uri;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.Message);
            }
            return null;
        }
    }
    internal class Program
    {
        public static async Task Main(string[] args)
        {
            // 代理服务器信息  
            var host = DynamicCploar.GetGrassWebProxyHost("ipport.json");
            string proxyAddress = host.Host;
            int proxyPort = host.Port; // 代理服务器的端口  
                                   // 创建HttpClientHandler并设置代理  
            var handler = new HttpClientHandler
            {
                Proxy = new WebProxy(proxyAddress, proxyPort),
                UseProxy = true, // 默认情况下UseProxy是true,但明确设置可以避免混淆  
                                 // 如果代理服务器需要认证,可以添加以下两行(替换username和password)  
                                 // Proxy = new WebProxy(proxyAddress, proxyPort)  
                                 // {  
                                 //     Credentials = new NetworkCredential("username", "password")  
                                 // },  
            };
            using (HttpClient client = new HttpClient(handler))
            {
                string url = "https://www.iciba.com/";
                //加Headers["X-Proxy-Ticket"]
                var ticket = GP.ReadConfig("Ticket1.json");
                //"G" 71 0x47
                //"P" 80 0x50
                byte[] tickBytes = new byte[10];
                tickBytes[0] = 0x47;
                tickBytes[1] = 0x50;
                Buffer.BlockCopy(BitConverter.GetBytes(ticket.TicketNo), 0, tickBytes, 2, 8);
                string ticketHeader = Encoding.UTF8.GetString(tickBytes);
                // 设置请求头  
                client.DefaultRequestHeaders.Add("X-Proxy-Ticket", ticketHeader);
                HttpResponseMessage response = await client.GetAsync(url);

                response.EnsureSuccessStatusCode(); // 抛出异常如果状态码表示错误  
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseBody);
            }
        }
    }
}

GrassWebProxyClientV5:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.IO.Compression;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace GrassWebProxyClientV5
{
    public class IPport
    {
        public string IP { get; set; }
        public int Port { get; set; }
    }
    public class CpolarInfo
    {
        public int total { get; set; }
        public item[] items { get; set; }
    }
    public class item
    {
        public string name { get; set; }
        public string create_datetime { get; set; }
        public string pubulic_url { get; set; }
    }
    public class CustomDateTimeConverter : IsoDateTimeConverter
    {
        public CustomDateTimeConverter()
        {
            DateTimeFormat = "yyyyMMdd'T'HH:mm:ss";
        }
    }
    public class Ticket
    {
        public ulong TicketNo { get; set; }

        [JsonConverter(typeof(CustomDateTimeConverter))]
        public DateTime BeginDateTime { get; set; }

        [JsonConverter(typeof(CustomDateTimeConverter))]
        public DateTime EndDateTime { get; set; }
    }
    public class GP
    {
        public static bool CheckFlag(ref byte[] msg)
        {
            //"G" 71 0x47
            //"P" 80 0x50
            if (msg[0] == 0x47 && msg[1] == 0x50)
            {
                Console.WriteLine("CheckFlag OK");
                return true;
            }
            return false;
        }
        static public Ticket ReadConfig(string cfg = "Ticket1.json")
        {
            // 读取文件内容  
            string jsonContent = File.ReadAllText(cfg);

            // 反序列化JSON字符串到对象  
            Ticket ticket = JsonConvert.DeserializeObject<Ticket>(jsonContent);
            // 输出结果  
            Console.WriteLine($"{ticket.TicketNo}\r\n{ticket.BeginDateTime}---{ticket.EndDateTime}");
            return ticket;
        }
        static public bool CheckTicket(ref byte[] msg, Ticket counterfoil)
        {
            /*ulong ticket = (ulong)((msg[2] << 56) | (msg[3] << 48) | (msg[4] << 40)
                | (msg[5] << 32) | (msg[6] << 24) | (msg[7] << 16) | (msg[8] << 8) | msg[9]);*/
            ulong ticket = BitConverter.ToUInt64(msg, 2); // 从索引2开始读取8个字节
                                                          //Console.WriteLine(ticket.ToString("X"));
            if (counterfoil.TicketNo == ticket)
            {
                return true;
            }
            return false;
        }
        static public bool CheckFlagAdTicket(ref byte[] msg, Ticket counterfoil)
        {
            //"G" 71 0x47
            //"P" 80 0x50
            ulong ticket = BitConverter.ToUInt64(msg, 2); // 从索引2开始读取8个字节
            if (msg[0] == 0x47 && msg[1] == 0x50 && counterfoil.TicketNo == ticket)
            {
                return true;
            }
            return false;
        }

        public static byte[] Compress(byte[] input)
        {
            using (var memoryStream = new MemoryStream())
            {
                using (var gzipStream = new GZipStream(memoryStream, CompressionMode.Compress, true))
                {
                    gzipStream.Write(input, 0, input.Length);
                }

                // 确保所有数据都被写入并压缩  
                return memoryStream.ToArray();
            }
        }
        public static byte[] DecompressGzip(byte[] gzip, int prebytes = 4096)
        {
            using (var ms = new MemoryStream(gzip))
            {
                using (var gzipStream = new GZipStream(ms, CompressionMode.Decompress))
                {
                    var buffer = new byte[prebytes];
                    using (var memoryStreamOut = new MemoryStream())
                    {
                        int read;
                        while ((read = gzipStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            memoryStreamOut.Write(buffer, 0, read);
                        }
                        return memoryStreamOut.ToArray();
                    }
                }
            }
        }
    }

    public class DynamicCploar
    {
        public static Uri GetGrassWebProxyHost(string notifyServer = "ipport.json")
        {
            try
            {
                // 读取文件内容  
                string jsonContent = File.ReadAllText(notifyServer);

                // 反序列化JSON字符串到对象  
                IPport ipaddr = JsonConvert.DeserializeObject<IPport>(jsonContent);

                // 输出结果  
                Console.WriteLine($"Notify Server: {ipaddr.IP}:{ipaddr.Port}");

                // 创建一个TcpClient实例并连接到服务器  
                TcpClient client = new TcpClient($"{ipaddr.IP}", ipaddr.Port);

                // 获取一个NetworkStream对象以进行读写  
                NetworkStream stream = client.GetStream();

                // 将消息转换为字节数组  
                //string message = "Hello from the client!";
                //byte[] data = Encoding.ASCII.GetBytes(message);
                byte[] data = { 0x4E, 0x74, 0x01, 0xF2, 0x00, 0x00, 0x00, 0x01 };

                // 发送消息到服务器  
                stream.Write(data, 0, data.Length);

                // 读取服务器的响应  
                byte[] buffer = new byte[1024];
                int bytesRead = stream.Read(buffer, 0, buffer.Length);

                // 将接收到的字节转换为字符串  
                string responseData = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                //Console.WriteLine("Received from server: " + responseData);
                //Console.WriteLine("ReceivedBytes:{0}", bytesRead);
                // 关闭连接  
                client.Close();
                //将Json写入文件
                File.WriteAllText("cpolarinfo.json", responseData);

                CpolarInfo cpinfo = new CpolarInfo();
                if (responseData == string.Empty)
                {
                    responseData = File.ReadAllText("cpolarinfo.json");
                }
                else
                {
                    //
                    Console.WriteLine(responseData);
                    cpinfo = JsonConvert.DeserializeObject<CpolarInfo>(responseData);
                    //Console.WriteLine($"{cpinfo.total}");
                    //for (int i = 0; i < cpinfo.total; i++)
                    //{
                    //    Console.WriteLine($"{cpinfo.items[i].name}\r\n{cpinfo.items[i].create_datetime}\r\n{cpinfo.items[i].pubulic_url}");
                    //}
                }

                string host = string.Empty;
                for (int i = 0; i < cpinfo.total; i++)
                {
                    if (cpinfo.items[i].name == "GrassWebProxy")
                    {
                        host = cpinfo.items[i].pubulic_url;
                    }
                }
                Console.WriteLine(host);
                // 使用Uri类来解析URL(这是更推荐的方法,因为它更健壮且能处理各种URL格式)  
                Uri uri = new Uri(host);

                return uri;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.Message);
            }
            return null;
        }
    }
    internal class Program
    {
        static void UseWebProxy(string webProxyUrl, string ip, int port)
        {
            try
            {
                string jsonFilePath = "Ticket1.json";
                // 读取文件内容  
                string jsonContent = File.ReadAllText(jsonFilePath);
                // 反序列化JSON字符串到对象  
                Ticket ticket = JsonConvert.DeserializeObject<Ticket>(jsonContent);

                // 输出结果  
                Console.WriteLine($"{ticket.TicketNo},{ticket.BeginDateTime.ToString("yyyyMMdd'T'HH:mm:ss")}---{ticket.EndDateTime.ToString("yyyyMMdd'T'HH:mm:ss")}");
                //组装
                byte[] data = { 0x47, 0x50, 0x01, 0xF2, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01 };
                for (int i = 2, j = 7; i < data.Length; i++, j--)
                {
                    data[i] = (byte)(ticket.TicketNo >> (j * 8));
                    //Console.WriteLine(data[i]);
                }

                // 将消息转换为字节数组  
                // 将 data 和 requestdata 合并到 buffer 中  
                byte[] requestdata = Encoding.UTF8.GetBytes(webProxyUrl);
                byte[] buf = new byte[data.Length + requestdata.Length];
                Buffer.BlockCopy(data, 0, buf, 0, data.Length);
                Buffer.BlockCopy(requestdata, 0, buf, data.Length, requestdata.Length);

                // 创建一个TcpClient实例并连接到服务器  
                TcpClient client = new TcpClient(ip, port);

                // 获取一个NetworkStream对象以进行读写  
                NetworkStream stream = client.GetStream();
                // 发送消息到服务器
                stream.Write(buf, 0, buf.Length);

                // 读取服务器的响应  
                byte[] buffer = new byte[81920];
                int totalBytesRead = 0;
                int bytesRead = 0;
                string responseData = string.Empty;

                while ((bytesRead = stream.Read(buffer, totalBytesRead, buffer.Length - totalBytesRead)) > 0)
                {
                    Console.WriteLine("ReceivedBytes:{0}", bytesRead);
                    totalBytesRead += bytesRead;
                }
                // 关闭连接  
                client.Close();

                //解压
                var tmp = GP.DecompressGzip(buffer,totalBytesRead);
                // 将接收到的字节转换为字符串  
                responseData = Encoding.UTF8.GetString(tmp, 0, tmp.Length);

                // 现在 totalBytesRead 包含了从流中读取的总字节数
                Console.WriteLine("TotalReceivedBytes:{0}", totalBytesRead);
                Console.WriteLine("Received from server:\r\n" + responseData);


                //将Json写入文件
                File.WriteAllText("response.html", responseData);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.Message);
            }
        }
        static void Main(string[] args)
        {
            // 代理服务器信息  
            var host = DynamicCploar.GetGrassWebProxyHost("ipport.json");
            //string proxyAddress = host.Host;
            //int proxyPort = host.Port; // 代理服务器的端口  
                                       // 创建HttpClientHandler并设置代理  

            UseWebProxy("https://www.baidu.com/",host.Host,host.Port);
            string url="https://access-hsk.oray.com/loading?r=https%253A%252F%252Fu1506257x0%252Egoho%252Eco%253A443%252Fhtml%252Fopendata%252Ehtml&i=aHR0cHM6Ly91MTUwNjI1N3gwLmdvaG8uY286NDQzLDE0LjE1MS44MS43Mg%253D%253D&p=2979654771&k=aHV4eWNjXzE0LjE1MS44MS43Ml9FZGdlXzEyNyUyRTAlMkUwJTJFMF9XaW5kb3dzX1dpbmRvd3MlMjAxMA%3D%3D";
            UseWebProxy(url, host.Host, host.Port);
            url = "http://www.cjors.cn/";
            UseWebProxy(url, host.Host, host.Port);
        }
    }
}


http://www.kler.cn/a/539765.html

相关文章:

  • 数组与指针1
  • JAVA中的抽象学习
  • Linux:库
  • 第433场周赛:变长子数组求和、最多 K 个元素的子序列的最值之和、粉刷房子 Ⅳ、最多 K 个元素的子数组的最值之和
  • 聚类算法概念、分类、特点及应用场景【机器学习】【无监督学习】
  • Linux系统-centos防火墙firewalld详解
  • MySQL索引深度解析:从原理到优化
  • 大语言模型RAG,transformer和mamba
  • go语言中的反射
  • JavaScript系列(64)--响应式状态管理实现详解
  • webpack系统学习
  • RK3568使用C++和FFmpeg进行视频流,并使用自带GPU加速
  • 寒假2.7
  • Springboot原理(面试高频)
  • Linux | 自动化构建 —— make / Makefile
  • 导航守卫router.beforeEach
  • 设计模式.
  • F#语言的物联网
  • Linux0号进程的静态创建
  • 如何在 Vue 中使用 mixins?
  • HTML之CSS定位、浮动、盒子模型
  • Spring AI 介绍
  • 【设计模式】【行为型模式】策略模式(Strategy)
  • windows下搭建tftp服务器+网络启动Linux
  • 苹果可折叠iPad:2028年的科技盛宴?
  • 30~32.ppt