/**
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;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

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;
private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true; //总是接受
}
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.
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);

HttpWebRequest req = (HttpWebRequest)WebRequest.Create
(strClientConnection);
req.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506; .NET CLR 3.5.21019)";
// req.Headers.Add("UserAgent", "Mozilla/5.0 (Windows NT 6.1; rv:40.0) Gecko/20100101 Firefox/40.0");

// 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);
try
{
sock.Send(buffer, len, 0);
}
catch (Exception e) {
Console.WriteLine(e.Message);
}
}

// 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# ProxyServer 代理服务器 不是很稳定的更多相关文章

  1. proxy server 代理服务器

    有时候,我觉得自己需要去搞明白.搞清楚一个概念,帮我打通一下自己的知识体系,或者说,尝试联络起来. 1. 简介 突破自身IP限制,访问国外站点. 访问单位或者团体内部资源. 突破中国电信的IP封锁. ...

  2. 搞JAVA在北京月薪15K的朋友来到厦门却很难找到工作

    朋友是搞JAVA开发的,从北京来.来前朋友们都感觉他在厦门应该很快就能找到工作,因为厦门的IT人员很缺. 没想到来厦门大概半个多月了,到现在都还没着落.面试单位每周基本只有两家,而且面试的感觉都说不错 ...

  3. HttpClient支持使用代理服务器以及身份认证

    HttpClient Authentication Doument: http://hc.apache.org/httpclient-3.x/authentication.html HttpClien ...

  4. 国外稳定的免费PHP空间byethost.com

    byethost.com是一个老牌的免费空间商,从2006年起就開始提供免费空间了,其免费服务很稳定(看完下文你就知道有多稳定了). 提供5.5G的免费空间,200G的月流量,能够绑定50个域名,也能 ...

  5. 跨域问题实践总结!下( [HTML5] postMessage+服务器端(反向代理服务器+CORS Cross-Origin Resource Sharing))

    4. [HTML5] postMessage 问题: 对于跨域问题,研究了一下html5的postMessage,写了代码测试了一下,感觉html5新功能就是好用啊.此文仅使用html5的新特性pos ...

  6. wine安装稳定使用falsh播放器

    1安装wine,wine安装使用网上自行查找 2.安装flash播放器.exe 下载附件的falsh播放相关.tar.gz,解压后得到 Flash.ocx (flash10 for windows的插 ...

  7. idea 启动 springBoot debug很慢,正常启动很快是什么原因

    说实话,从我开始使用springboot框架以来,就一直遇到这个问题,我刚把项目从SSM框架转成 spring boot 框架时,就发现有时候启动项目特别慢,有时候特别快,当时觉得特别奇怪,但也一直没 ...

  8. DIOCP开源项目-DIOCP3的重生和稳定版本发布

    DIOCP3的重生 从开始写DIOCP到现在已经有一年多的时间了,最近两个月以来一直有个想法做个 30 * 24 稳定的企业服务端架构,让程序员专注于逻辑实现就好.虽然DIOCP到现在通讯层已经很稳定 ...

  9. 让Selenium稳定运行的技巧

    Selenium简介 Selenium是非常流行的Web自动化测试工具.它具有自动化测试用例制作简单,支持多种浏览器和不同的操作系统等优点. Selenium脚本不稳定的问题 有很多时候Seleniu ...

随机推荐

  1. 关于String的问题

    String是在代码中非常常见的一种数据类型.它能直接像基本类型一样直接赋值(String str = "test"),也能像引用类型一样创建一个实例(String str = n ...

  2. 加盟全景-加盟VR虚拟现实-全景智慧城市

    作为一个技术整合型产业,VR行业的硬件厂商几乎没有任何技术基础,很多国产虚拟现实VR创业公司基本都是和几家固定的上游零部件提供商合作,全行业都在等待高通骁龙芯片的升级,这和手机行业有几分相似.去年3月 ...

  3. 史诗手册!微信小程序新手自学入门宝典!

    一.小程序官方指南 1:官方开发工具下载: https://mp.weixin.qq.com/debug/wxadoc/dev/devtools/download.html?t=201714 0.12 ...

  4. 写给Android App开发人员看的Android底层知识(4)

    (八)App内部的页面跳转 在介绍完App的启动流程后,我们发现,其实就是启动一个App的首页. 接下来我们看App内部页面的跳转. 从ActivityA跳转到ActivityB,其实可以把Activ ...

  5. kotlin语言使用初体验(一)

    居说谷歌新认的干儿子kotlin极为受宠,隐隐有替代Java在 android平台老大位置的趋势.kotlin有谷歌撑腰,加上自己的底子也厚,再之与Java无缝兼容,将来在流行的编程语言中占有一席之地 ...

  6. ES6解构赋值详解

    文章转载自:http://www.zhufengpeixun.cn/article/167 解构赋值(destructuring assignment)语法是一个 Javascript 表达式,这种语 ...

  7. javaSE_06Java中的数组(array)

    1.什么是数组? 顾名思义,即为数据的组合或集合,数组就是用来表示一组数据的. 比如没有数组之前,我们要存储多个姓名的信息 String name1; String name2; String nam ...

  8. IPv6启动五年后,距离我们究竟还有多远?

    作者:RicardoIPv6拥有更好的IP拓展性,更高的安全保障以及更快的传输速度,互联网协会将2012年6月6日定为了世界IPv6启动日,距此5年后,国内外Cloudflare.又拍云等CDN服务已 ...

  9. vue-cli项目中怎么mock数据

    在vue项目中, mock数据可以使用 node 的 express模块搭建服务 1. 在根目录下创建 test 目录, 用来存放模拟的 json 数据, 在 test 目录下创建模拟的数据 data ...

  10. Android Apk的反编译和加密

    这几天在上海出差,忙里偷闲学习了一下Apk的反编译工具的基本使用.下面就简单介绍一下如何将我们从网上下载的Apk文件进行反编译得到我们想要获得的资源文件和源码. Android的应用程序APK文件说到 ...