图片使用说明
1. 编译运行:将代码保存为.cs文件,使用dotnet run启动
2. 浏览器设置:将浏览器代理设置为127.0.0.1:8888
3. 测试验证:访问任意网站,查看控制台输出
常见坑点提醒
- 端口占用确保选择的端口未被其他程序占用
- 防火墙设置可能需要添加防火墙规则允许程序监听端口
- 超时处理网络超时会导致连接挂起,代码中已添加超时控制
方案二:带请求监控的高级代理服务器
功能增强点
在基础版本的基础上,我们来实现一个企业级的高级代理服务器,新增以下核心功能:
1. 请求监控:记录每个请求的详细信息和响应时间
2. 域名过滤:支持黑名单机制,自动阻止恶意域名访问
3. 统计分析:定时输出代理服务器运行统计
4. 日志导出:支持将请求日志导出为JSON格式
5. 性能监控:实时监控数据传输量和响应时间
核心监控代码实现
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Collections.Concurrent;
using System.Text.Json;
namespace AppBasicHttpProxyServer
{
/// <summary>
/// 带请求监控的高级代理服务器
/// </summary>
publicclass AdvancedHttpProxyServer
{
private readonly int _port;
private TcpListener _listener;
privatebool _isRunning;
// 请求监控和统计
private readonly ConcurrentQueue<RequestLog> _requestLogs;
private readonly ConcurrentDictionary<string, DomainStats> _domainStats;
private readonly object _statsLock = new object();
// 配置选项
private readonly ProxyConfig _config;
public AdvancedHttpProxyServer(int port = 8888, ProxyConfig config = null)
{
_port = port;
_requestLogs = new ConcurrentQueue<RequestLog>();
_domainStats = new ConcurrentDictionary<string, DomainStats>();
_config = config ?? new ProxyConfig();
// 启动监控任务
if (_config.EnableMonitoring)
{
_ = Task.Run(MonitoringTaskAsync);
}
// 启动日志清理任务
if (_config.EnableLogCleanup)
{
_ = Task.Run(LogCleanupTaskAsync);
}
}
/// <summary>
/// 启动代理服务器
/// </summary>
public async Task StartAsync()
{
_listener = new TcpListener(IPAddress.Any, _port);
_listener.Start();
_isRunning = true;
Console.WriteLine("