欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-11-20 22:31:58
本文实例讲述了c#实现多线程的web代理服务器。分享给大家供大家参考。具体如下: /** proxy.cs: c# programming tips & te...

本文实例讲述了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#程序设计有所帮助。