Hi i'm newbie about c# socket, i'm trying to practice creating a proxy server. The request from browser display correctly (GET ...). So i create new socket to connect to destination, everything is ok, i got response with HTTP/1.1 200 ... but the rest part that must be <html>... as i know, it turn out to be some weird characters. My browser display massage like "Cannot load content ...". This is my code:
class Program
{
static void Main(string[] args)
{
int port = 1989;
TcpListener tcp = new TcpListener(port);
tcp.Start();
while (true)
{
Socket soc = tcp.AcceptSocket();
Test e = new Test(soc);
Thread t = new Thread(new ThreadStart(e.Run));
t.Start();
}
}
}
class Test
{
Socket s;
public Test(Socket v)
{
s = v;
}
public void Run()
{
byte[] buff = new byte[1024];
int rbuff = 0;
byte[] data = new byte[1024];
int rdata = 0;
rbuff = s.Receive(buff, 0, buff.Length, SocketFlags.None);
if (rbuff > 0)
{
string s1 = Encoding.UTF8.GetString(buff);
int at = s1.IndexOf("\r\n", 0);
int at1 = s1.IndexOf("\r\n", at+2);
s1 = s1.Substring(0, at1);
s1 = s1.Replace("\r\n", " ");
string[] str = s1.Split(' ');
Console.WriteLine(str[4]);
IPHostEntry ih = Dns.Resolve(str[4]);
IPEndPoint ie = new IPEndPoint(ih.AddressList[0], 80);
Socket soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
soc.Connect(ie);
if (soc.Connected)
{
Console.WriteLine("Ket noi toi: {0}", ih.AddressList[0]);
byte[] rcv = new byte[1024];
int i = 0;
rbuff = soc.Send(buff, 0, buff.Length, SocketFlags.None);
if (rbuff > 0)
Console.WriteLine("Goi dc toi server");
do
{
i += soc.Receive(rcv, 0, rcv.Length, SocketFlags.None);
if (i > 0)
{
Console.WriteLine("nhan dc {0} Byte", i);
rdata = s.Send(rcv, 0, rcv.Length, SocketFlags.None);
if (rdata > 0)
Console.WriteLine("Goi Thnah cong");
}
} while (i > 0);
}
else
{
string s2 = "<HTML><BODY>Ko goi nhan dc</BODY></HTML>";
data = Encoding.UTF8.GetBytes(s2);
rdata = s.Send(data, 0, data.Length, SocketFlags.None);
}
}
s.Shutdown(SocketShutdown.Both);
s.Close();
}
}
because of testing, my code is untidy, i appreciate any help, Thank for reading!
P/S: my English skill is not good, pls excuse me.