/**
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. 单词计数,杭电0j-2072

    原题地址:http://acm.hdu.edu.cn/showproblem.php?pid=2072 [Problem Description] lily的好朋友xiaoou333最近很空,他想了一 ...

  2. 详解Struts2拦截器机制

    Struts2的核心在于它复杂的拦截器,几乎70%的工作都是由拦截器完成的.比如我们之前用于将上传的文件对应于action实例中的三个属性的fileUpload拦截器,还有用于将表单页面的http请求 ...

  3. Servlet 详解

    1.什么是 Servlet? Java Servlet 是运行在 Web 服务器或应用服务器上的程序,它是作为来自 Web 浏览器或其他 HTTP 客户端的请求和 HTTP 服务器上的数据库或应用程序 ...

  4. Java 8——Optional

    本文主要介绍Java 8的 Optional 的简单使用 Address 1 2 3 4 5 6 7 @Data @AllArgsConstructor @NoArgsConstructor publ ...

  5. 【JAVAEE学习笔记】hibernate01:简介、搭建、配置文件详解、API详解和CRM练习:保存客户

    今日学习:hibernate是什么 一.hibernate是什么 框架是什么: 1.框架是用来提高开发效率的 2.封装了好了一些功能.我们需要使用这些功能时,调用即可.不需要再手动实现. 3.所以框架 ...

  6. ASP微信开发获取用户经纬度

    wx.config({ //debug: true, debug: true, appId: '<%= appId %>', timestamp: '<%= timestamp %& ...

  7. textarea placeholder文字换行

    要实现这样的效果 第一反应是直接在placeholder属性值里输入\n换行,如: <textarea rows="5" cols="50" placeh ...

  8. 【2017-06-05】Jquery.ajax

    AJAX  是一种网页数据异步加载技术 通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新.这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新. 一.Json     ...

  9. phpcms插件

    最近在研究PHP,学了一段时间后感觉想自己写点东西,但是又不知道写什么,最后把目标对准了PHPCMS的插件,从网上找了一下,大部分教程都只是教怎么写插件的具体代码,而没有教怎么把插件打成安装包,特别是 ...

  10. 关于JQuery获取宽度和高度在chrome和IE下的不同

    之前写了一个关于滚动条的东西,可是在写的时候发现JQuery在获取宽度和高度时在不同浏览器中是不一样的,下面发一下代码给给位看官先展示一下: $(function(){ $("#main&q ...