csharp tcp代理

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp tcp代理相关的知识,希望对你有一定的参考价值。

using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace Proxy
{
    class Program
    {
        static void Main(string[] args)
        {
            int localPort = int.Parse(args[0]);
            int openPort = int.Parse(args[1]);

            Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            listener.Bind(new IPEndPoint(IPAddress.Any, openPort));
            listener.Listen(10);

            while (true)
            {
                var c = listener.Accept();
                var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                s.Connect(new IPEndPoint(IPAddress.Loopback, localPort));
                Thread serverThread = new Thread(o =>
                {
                    byte[] stuff = new byte[1024];
                    try
                    {
                        while (true)
                        {
                            int count = s.Receive(stuff);
                            if (count == 0)
                            {
                                s.Close();
                                return;
                            }
                            c.Send(stuff, count, SocketFlags.None);
                        }
                    }
                    catch (Exception)
                    {
                        s.Close();
                        c.Close();
                    }
                });
                Thread clientThread = new Thread(o =>
                {
                    try
                    {
                        byte[] stuff = new byte[1024];
                        try
                        {
                            while (true)
                            {
                                int count = c.Receive(stuff);
                                if (count == 0)
                                {
                                    c.Close();
                                    return;
                                }
                                s.Send(stuff, count, SocketFlags.None);
                            }
                        }
                        catch (Exception)
                        {
                            s.Close();
                            c.Close();
                        }
                    }
                    catch (Exception)
                    {
                    }
                });
                serverThread.Start();
                clientThread.Start();
            }
        }
    }
}

以上是关于csharp tcp代理的主要内容,如果未能解决你的问题,请参考以下文章

csharp 设计图案结构代理

csharp 使用简单代理的示例服务类

csharp 从AD #exchange下载所有代理地址

csharp Берём代理

csharp 外部服务的简单代理。通过将callout分解为代理类来最小化接近外部服务调用的未经测试的代码。

csharp 使用基本身份验证和代理的简单C#.NET 4.5 HTTPClient请求