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

作者:红薯 时间:2022-02-25 13:32:08 

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

标签:C#,多线程
0
投稿

猜你喜欢

  • 微信小程序与AspNetCore SignalR聊天实例代码

    2022-12-21 01:29:06
  • SpringBoot+WebSocket实现多人在线聊天案例实例

    2022-08-22 11:53:08
  • 详解Springboot自定义异常处理

    2021-11-04 17:15:12
  • Java多线程-线程的同步与锁的问题

    2023-11-29 01:40:12
  • 解决spring mvc 多数据源切换,不支持事务控制的问题

    2022-09-30 03:39:56
  • SpringBoot错误处理机制以及自定义异常处理详解

    2021-09-23 05:45:29
  • Java 定时任务技术趋势详情

    2021-10-29 14:48:13
  • SpringBoot配置全局异常处理器捕获异常详解

    2023-11-28 05:08:07
  • c# winform时钟的实现代码

    2023-04-05 07:40:53
  • winform把Office转成PDF文件

    2023-03-29 01:09:32
  • MyBatis一二级缓存

    2021-07-03 13:01:59
  • 解决MyBatis @param注解参数类型错误异常的问题

    2023-12-01 06:41:45
  • Mybatis的mapper.xml中if标签test判断的用法说明

    2023-12-23 23:04:16
  • C#静态static的用法实例分析

    2022-06-30 09:37:27
  • c#方法中调用参数的值传递方式和引用传递方式以及ref与out的区别深入解析

    2023-04-07 03:43:25
  • 解析maven的用法和几个常用的命令(推荐)

    2022-04-16 23:31:15
  • Java自定义标签用法实例分析

    2023-02-28 21:58:55
  • Java File类的概述及常用方法使用详解

    2023-11-28 13:06:28
  • java跟踪执行的sql语句示例分享

    2022-07-30 20:13:18
  • Java在PDF中添加表格过程详解

    2022-12-24 20:32:04
  • asp之家 软件编程 m.aspxhome.com