SoFunction
Updated on 2025-03-08

C# implements multi-threaded web proxy server instance

This article describes the C# implementation of multi-threaded web proxy server. Share it for your reference. The details are as follows:

/**
:
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
//  -- Implements a multi-threaded Web proxy server
//
//    Compile this program with the following command line:
//     C:>csc 
using System;
using ;
using ;
using ;
using ;
using ;
namespace nsProxyServer
{
 public class ProxyServer
 {
  static public void Main (string [] args)
  {
   int Port = 3125;
   if ( > 0)
   {
    try
    {
     Port = Convert.ToInt32 (args[0]);
    }
    catch
    {
      ("Please enter a port number.");
     return;
    }
   }
   try
   {
    // Create a listener for the proxy port
    TcpListener sockServer = new TcpListener (Port);
     ();
    while (true)
    {
     // Accept connections on the proxy port.
     Socket socket =  ();
     // 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 ());
      ();
     // While the thread is running, the main program thread will loop around
     // and listen for the next connection request.
    }
   }
   catch (IOException e)
   {
     ();
   }
  }
 }
 class clsProxyConnection
 {
  public clsProxyConnection (Socket sockClient)
  {
   m_sockClient = sockClient;
  }
  Socket m_sockClient; //, m_sockServer;
  Byte [] readBuf = new Byte [1024];
  Byte [] buffer = null;
  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 =  (' ');
    int index2 =  (' ', index1 + 1);
    string strClientConnection =
       (index1 + 1, index2 - index1);
    if ((index1 < 0) || (index2 < 0))
    {
     throw (new IOException ());
    }
    // Write a messsage that we are connecting.
     ("Connecting to Site " +
         strClientConnection);
     ("Connection from " +
         m_sockClient.RemoteEndPoint);
    // Create a WebRequest object.
    WebRequest req = (WebRequest) 
              (strClientConnection);
    // Get the response from the Web site.
    WebResponse response =  ();
    int BytesRead = 0;
    Byte [] Buffer = new Byte[32];
    int BytesSent = 0;
    // Create a response stream object.
    Stream ResponseStream = ();
    // Read the response into a buffer.
    BytesRead = (Buffer,0,32);
    StringBuilder strResponse = new StringBuilder("");
    while (BytesRead != 0)
    {
     // Pass the response back to the client
     ((Buffer,
          0, BytesRead));
     m_sockClient.Send(Buffer, BytesRead, 0);
     BytesSent += BytesRead;
     // Read the next part of the response
     BytesRead = (Buffer, 0, 32);
    }
   }
   catch (FileNotFoundException e)
   {
    SendErrorPage (404, "File Not Found", );
   }
   catch (IOException e)
   {
    SendErrorPage (503, "Service not available", );
   }
   catch (Exception e)
   {
     SendErrorPage (404, "File Not Found", );
      ();
      ();
   }
   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 [ + 1];
   int len =  ((),
          0, , buffer, 0);
    (buffer, len, 0);
  }
  // Read a string from a socket.
  int ReadMessage (Socket sock, byte [] buf, ref string strMessage)
  {
   int iBytes =  (buf, 1024, 0);
   strMessage =  (buf);
   return (iBytes);
  }
 }
}

I hope this article will be helpful to everyone's C# programming.