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
投稿
猜你喜欢
Java-String类最全汇总(上篇)
2023-04-15 11:47:10
浅谈java中静态方法的重写问题详解
2022-12-24 10:13:04
C# 泛型字典 Dictionary的使用详解
2022-01-19 23:48:17
SpringBoot实现监控Actuator,关闭redis监测
2021-08-01 04:01:33
Lombok中@EqualsAndHashCode注解的使用及说明
2023-11-30 04:47:05
Android串口通讯SerialPort的使用详情
2022-03-08 00:23:46
feign 如何获取请求真实目的ip地址
2021-08-13 15:47:49
Java多线程 ReentrantLock互斥锁详解
2022-07-23 21:21:06
java中transient关键字用法分析
2022-01-22 04:27:05
WPF换肤设计原理浅析
2022-11-18 00:37:00
c#字符串编码编码(encoding)使用方法示例
2022-10-04 07:24:58
Qt GUI图形图像开发之Qt表格控件QTableView简单使用方法及QTableView与QTableWidget区别
2022-02-23 05:02:59
Android中如何安全地打印日志详解
2023-02-10 12:17:42
10道springboot常见面试题
2023-09-02 03:02:22
如何把VS Code打造成Java开发IDE
2021-09-16 16:37:36
C#中判断本地系统的网络连接状态的方法
2023-07-02 15:39:41
Unity通用泛型单例设计模式(普通型和继承自MonoBehaviour)
2023-08-24 14:53:28
详解Java中的Vector
2023-06-05 01:40:49
SpringMVC @NotNull校验不生效的解决方案
2021-07-19 23:20:07
android实现raw文件夹导入数据库代码
2023-07-02 04:26:28