C#实现多线程的Web代理服务器实例
作者:红薯 发布时间:2022-02-25 13:32:08
标签:C#,多线程
本文实例讲述了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#程序设计有所帮助。


猜你喜欢
- 当一个结合中想根据某一个字段做去重方法时使用以下代码IQueryable 继承自IEnumerable先举例:#region linq to
- 本文实例讲述了Spring和Hibernate的整合操作。分享给大家供大家参考,具体如下:一 web配置<?xml version=&
- Hadoop环境搭建详见此文章https://www.jb51.net/article/33649.htm。我们已经知道Hadoop能够通过
- 首先需要有网络权限,然后我们这里匹配的网络请求是之前封装好的Okhttp。非常的简单方便,直接复制进去,依赖一下包,然后调用方法即可。 这里
- Maven Release当我们的项目达到了当前的目标,在经过检测后不需要改变。这时我们就需要将SNAPSHOT版本打包成RELEASE版本
- 本文为大家分享两个实例,相信大家一定会喜欢。实例1:随机生成验证码图片并将之输出为一个png文件效果图:import java.awt.Co
- FeignClient设置动态Url1. 需求描述一般情况下,微服务内部调用都是通过注册中心,eureka,zookeeper,nacos等
- 引言最近,因为开发的时候经改动依赖的库,所以,我想对 Gradle 脚本做一个调整,用来动态地将依赖替换为源码。这里以 android-mv
- 项目背景:在项目中包含两个定时任务,配置信息如下:1、@Scheduled(initialDelay = 1,fixedDelay=1000
- RecyclerView上拉加载,先看效果:网上有很多这类得框架,不过在自己的项目只用到上拉加载的功能,所以自己封装一个简单点的。主要依赖B
- 由于MediaPlayer占用资源较多,且不支持同时播放多个音频,所以Android还提供了另一个播放音频的类-----SoundPool。
- 有关临时对象的生命周期有三种情况:1)一般情况:临时性对象的被摧毁,应该是对完整表达式(full-expression)求值过程中的最后一个
- 本文实例为大家分享了Java实现简单邮件发送的具体代码,供大家参考,具体内容如下需要的jar包:activation-1.1.1.jarma
- Android Notification使用详解Notification核心代码(链式调用):适用于Android 4.0以上(
- 前后端分离的项目,前端有菜单(menu),后端有API(backendApi),一个menu对应的页面有N个API接口来支持,本文介绍如何基
- 本文实例为大家分享了android自定义环形对比图的具体代码,供大家参考,具体内容如下1.首先在res/values里创建一个attr.xm
- 这篇文章主要介绍了springmvc处理模型数据ModelAndView过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一
- java Long类型转为String类型1、Long.ValueOf("String")返回Long包装类型数据包装类
- 目录对象的创建创建方式对象的内存布局创建过程对象的内存分配分配方式并发安全代码优化逃逸分析的不成熟性实际的对象空间分配过程对象的访问句柄直接
- 前言本文主要给大家介绍了关于Android中GridView布局整体居中的相关内容,是对于自己在项目中遇到问题的一个记录,分享出来供大家参考