using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text.RegularExpressions;
namespace WebProxy
{
class Proxy
{
static void Main(string[] args)
{
const int port=9999;
TcpListener tcplistener = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 9999);
Console.WriteLine("侦听端口号:"+port.ToString());
tcplistener.Start();
//侦听端口号
while (true)
{
Socket socket=tcplistener.AcceptSocket();
//并获取传送和接收数据的Socket实例
Proxy proxy=new Proxy(socket);
//Proxy类实例化
Thread thread=new Thread (new ThreadStart(proxy.Run));
//创建线程
thread.Start();
//启动线程
}
}
public Proxy(Socket socket) {
// TODO 在此处添加构造函数逻辑
this.clientSocket=socket; }
Socket clientSocket;
Byte[] read = new byte[1024];
//定义一个空间,存储来自客户端请求数据包
Byte[] Buffer = null;
//设定编码
Byte[] RecvBytes = new Byte[4096];
public void Run()
{
string clientmessage="";
//存放来自客户端的HTTP请求字符串
string URL="";
//存放解析出地址请求信息
int bytes=ReadMessage(read,ref clientSocket, ref clientmessage);
if(bytes == 0)
{
return ;
}
int index1 = clientmessage.IndexOf(' ');
int index2 = clientmessage.IndexOf(' ', index1 + 1);
if ((index1 == -1) || (index2 == -1))
{
throw new IOException();
}
string part1 = clientmessage.Substring(index1 + 1, index2 - index1);
int index3 = part1.IndexOf('/', index1 + 8);
int index4 = part1.IndexOf(' ', index1 + 8);
int index5 = index4 - index3;
URL = part1.Substring(index1 + 4, (part1.Length - index5) - 8);