当前位置: 首页 > 编程文章 >

C#实现多线程Web代理服务器实例

C#实现多线程Web代理服务器实例

作者:顾安时间:2026-04-12 15:51:50浏览:839

本文展示了一个基于C#语言开发的多线程Web代理服务器实例。该程序利用System.Net.Sockets和System.Threading命名空间,通过创建独立的线程来处理客户端请求,实现了并发连接处理能力。代码涵盖了基本的Socket接收、数据解析及ASCII编码转换逻辑,为理解C#网络编程中的异步处理与资源管理提供了参考。

本文目录收起

C#多线程Web代理服务器实现

本示例演示了如何使用C#构建一个支持多线程处理的Web代理服务器。相关内容可供开发者在编写网络服务时参考借鉴。


/**
Proxy.cs:
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// Proxy.cs -- Implements a multi-threaded Web proxy server
//
//    Compile this program with the following command line:
//     C:>csc Proxy.cs
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.IO;
using System.Threading;
namespace nsProxyServer
{
 public class ProxyServer
 {
  static public void Main (string [] args)
  {
   int Port = 3125;
   if (args.Length > 0)
   {
    try
    {
     Port = Convert.ToInt32 (args[0]);
    }
    catch
    {
     Console.WriteLine ("Please enter a port number.");
     return;
    }
   }
   try
   {
    // Create a listener for the proxy port
    TcpListener sockServer = new TcpListener (Port);
    sockServer.Start ();
    while (true)
    {
     // Accept connections on the proxy port.
     Socket socket = sockServer.AcceptSocket ();
     // When AcceptSocket returns, it means there is a connection. Create
     // an instance of the proxy server class and start a thread running.
     clsProxyConnection proxy = new clsProxyConnection (socket);
     Thread thrd = new Thread (new ThreadStart (proxy.Run));
     thrd.Start ();
     // While the thread is running, the main program thread will loop around
     // and listen for the next connection request.
    }
   }
   catch (IOException e)
   {
    Console.WriteLine (e.Message);
   }
  }
 }
 class clsProxyConnection
 {
  public clsProxyConnection (Socket sockClient)
  {
   m_sockClient = sockClient;
  }
  Socket m_sockClient; //, m_sockServer;
  Byte [] readBuf = new Byte [1024];
  Byte [] buffer = null;
  Encoding ASCII = Encoding.ASCII;
  public void Run ()
  {
   string strFromClient = "";
   try
   {
    // Read the incoming text on the socket/
    int bytes = ReadMessage (m_sockClient,
           readBuf, ref strFromClient);
    // If it's empty, it's an error, so just return.
    // This will termiate the thread.
    if (bytes == 0)
     return;
    // Get the URL for the connection. The client browser sends a GET command
    // followed by a space, then the URL, then and identifer for the HTTP version.
    // Extract the URL as the string betweeen the spaces.
    int index1 = strFromClient.IndexOf (' ');
    int index2 = strFromClient.IndexOf (' ', index1 + 1);
    string strClientConnection =
      strFromClient.Substring (index1 + 1, index2 - index1);
    if ((index1 < 0) || (index2 < 0))
    {
     throw (new IOException ());
    }
    // Write a messsage that we are connecting.
    Console.WriteLine ("Connecting to Site " +
         strClientConnection);
    Console.WriteLine ("Connection from " +
         m_sockClient.RemoteEndPoint);
    // Create a WebRequest object.
    WebRequest req = (WebRequest) WebRequest.Create
              (strClientConnection);
    // Get the response from the Web site.
    WebResponse response = req.GetResponse ();
    int BytesRead = 0;
    Byte [] Buffer = new Byte[32];
    int BytesSent = 0;
    // Create a response stream object.
    Stream ResponseStream = response.GetResponseStream();
    // Read the response into a buffer.
    BytesRead = ResponseStream.Read(Buffer,0,32);
    StringBuilder strResponse = new StringBuilder("");
    while (BytesRead != 0)
    {
     // Pass the response back to the client
     strResponse.Append(Encoding.ASCII.GetString(Buffer,
          0, BytesRead));
     m_sockClient.Send(Buffer, BytesRead, 0);
     BytesSent += BytesRead;
     // Read the next part of the response
     BytesRead = ResponseStream.Read(Buffer, 0, 32);
    }
   }
   catch (FileNotFoundException e)
   {
    SendErrorPage (404, "File Not Found", e.Message);
   }
   catch (IOException e)
   {
    SendErrorPage (503, "Service not available", e.Message);
   }
   catch (Exception e)
   {
     SendErrorPage (404, "File Not Found", e.Message);
     Console.WriteLine (e.StackTrace);
     Console.WriteLine (e.Message);
   }
   finally
   {
    // Disconnect and close the socket.
    if (m_sockClient != null)
    {
     if (m_sockClient.Connected)
     {
      m_sockClient.Close ();
     }
    }
   }
   // Returning from this method will terminate the thread.
  }
  // Write an error response to the client.
  void SendErrorPage (int status, string strReason, string strText)
  {
   SendMessage (m_sockClient, "HTTP/1.0" + " " +
       status + " " + strReason + "\r\n");
   SendMessage (m_sockClient, "Content-Type: text/plain" + "\r\n");
   SendMessage (m_sockClient, "Proxy-Connection: close" + "\r\n");
   SendMessage (m_sockClient, "\r\n");
   SendMessage (m_sockClient, status + " " + strReason);
   SendMessage (m_sockClient, strText);
  }
  // Send a string to a socket.
  void SendMessage (Socket sock, string strMessage)
  {
   buffer = new Byte [strMessage.Length + 1];
   int len = ASCII.GetBytes (strMessage.ToCharArray(),
          0, strMessage.Length, buffer, 0);
   sock.Send (buffer, len, 0);
  }
  // Read a string from a socket.
  int ReadMessage (Socket sock, byte [] buf, ref string strMessage)
  {
   int iBytes = sock.Receive (buf, 1024, 0);
   strMessage = Encoding.ASCII.GetString (buf);
   return (iBytes);
  }
 }
}

期望上述关于C#程序设计的内容能为读者在实际开发中提供有益的帮助。

上一篇
Python多线程与队列协作实例解析

本文通过Python3代码示例,展示如何利用threading模块创建生产者和消费者线程,并使用queue.Queue实现线程间的数据传递。重点分析了daemon线程机制、join()阻塞原理以及task_done()对程序生命周期控制的影响,解释了为何在无限循环场景中不调用task_done()会导致主线程永久阻塞。

下一篇
Python多线程结合队列下载百度音乐的方法

本文介绍一种使用Python多线程和Queue队列机制批量下载百度音乐的方法。该脚本依赖BeautifulSoup解析HTML,支持Windows和Linux平台。通过定义目标歌手和保存路径,程序自动获取歌曲链接并利用线程池并发下载,目前默认仅处理第一页结果,用户可根据需求进行拓展。

相关文章

更多
Python多线程结合队列下载百度音乐的方法

本文介绍一种使用Python多线程和Queue队列机制批量下载百度音乐的方法。该脚本依赖BeautifulSoup解析HTML,支持Windows和Linux平台。通过定义目标歌手和保存路径,程序自动获取歌曲链接并利用线程池并发下载,目前默认仅处理第一页结果,用户可根据需求进行拓展。

2026.11.14 972
PHP结合Shell脚本实现伪多线程的方法

本文介绍利用Shell脚本中的后台运行符号&配合PHP代码,在Linux环境下实现伪多线程处理任务的方法。通过在Shell循环中调用php命令并附加&号,可将多个PHP进程推送到后台并行执行,从而加速如批量下载等耗时操作。

2026.10.11 968
基于OpenCv实现的人脸识别(附Python完整代码)

本文介绍使用Python和OpenCV库实现人脸识别系统的完整流程。系统涵盖人脸采集、预处理、特征提取及匹配识别等核心步骤,采用LBPH算法进行训练与预测。程序通过Tkinter构建图形界面,并利用多线程技术处理摄像头资源互斥,支持从摄像头实时录入新面容并进行刷脸识别。

2025.02.12 870
PHP模拟多线程类及Curl实现实例

PHP原生不支持真正的多线程,但可通过Web服务器机制或Curl多句柄模拟并发效果。本文介绍两种常见方案:一是基于HTTP重定向的Thread类,通过循环发起自身GET请求并行执行回调;二是利用curl_multi_init的多句柄管理类,支持批量设置URL和选项,适用于远程资源如图片的高效并行下载。

2026.08.26 822
Python并行处理技巧:多线程加速For循环实战

面对千万级数据量的处理需求,传统串行For循环耗时过长。本文介绍利用Python的multiprocessing.dummy模块(线程池)实现并行For循环,将3000万条出租车数据的处理时间从数天缩短至分钟级。同时结合Git项目成员信息获取场景,展示如何通过多线程共享资源并加锁避免冲突,实测速度提升约58倍,有效解决大规模数据处理中的性能瓶颈。

2026.09.09 771
Java实现异步调用的核心机制与代码示例

本文介绍在Java平台中通过多线程实现异步调用的三种核心角色:调用者、取货凭证和真实数据。当耗时操作无法立即返回结果时,系统先返回凭证,后续凭此获取数据。文章展示了基于Thread和Runnable实现的Request类及抽象类RequestContent,通过覆盖onSuccess和onFailure方法处理执行结果,从而模拟类似Ajax的异步请求效果。

2025.06.28 707

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。