/**
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. 透过 Delphi 使用二进位金钥做 AES 加密.

    从 1994 年开始,笔者就开始接触加密与网路安全的世界,从鲁立忠老师的指导当中获益良多,后来在台湾的元智大学就读研究所的时候,也以此为研究主题. 在当时,电子商务是显学,Visa跟 Master C ...

  2. 在已经部署svn 服务器上,搭建svn项目 成功版

    1.进入svn目录,建立版本库 svnadmin create svntest svntest为svn项目名称 2. hooks/ 目录下新建 post-commit 文件 [钩子脚本] #!/bin ...

  3. OAuth 2.0 / RCF6749 协议解读

    OAuth是第三方应用授权的开放标准,目前版本是2.0版,以下将要介绍的内容和概念主要来源于该版本.恐篇幅太长,OAuth 的诞生背景就不在这里赘述了,可参考 RFC 6749 . 四种角色定义: R ...

  4. jquery+js实现鼠标位移放大镜效果

    jQuery实现仿某东商品详情页放大镜效果 用jquery+js实现放大镜效果,效果大概如下图! 效果是不是大家很感兴趣,放大镜查看细节,下边大家可以详细看一看具体是怎么实现的.下边直接看代码! HT ...

  5. Java经典编程题50道之二十六

    请输入星期几的第一个字母来判断一下是星期几,如果第一个字母一样,则继续判断第二个字母. public class Example26 {    public static void main(Stri ...

  6. 【JAVAWEB学习笔记】29_文件的上传------commons-fileupload

    今天内容: 文件的上传------commons-fileupload 文件上传和下载的实质:文件的拷贝 文件上传:从本地拷贝到服务器磁盘上   客户端需要编写文件上传表单---->服务端需要编 ...

  7. js for循环 等腰三角形demo

    <script> for(var i=1;i<10;i++){ for(var j=1;j<10-i;j++){document.write(" ")} f ...

  8. DiscuzX3.1搬家全过程

    最近做了一个安全交流小社区,由于太卡了,之后换了服务器,要给论坛搬家 所以在这里写一下记录. 首先,搬家前要做好以下准备: 1.在网站后台-站长-数据库-备份-网站-Discuz! 和 UCenter ...

  9. Python的核心数据结构

    数据结构 例子 数字 1234,3.1415,3+4j 字符串 'spam'."grace's" 列表 [1,[2,'three'],4] 字典 {'food':'spam','t ...

  10. 搭建vue开发环境及各种报错处理

    1.安装node.js 参考教程:http://nodejs.cn/download/ 我的是windows 64位系统,以此为例: (1)打开 http://nodejs.cn/download/ ...