日期:2014-05-16  浏览次数:20890 次

如何使用Socket来模拟HTTP请求与相应
如题!!!
我的服务器想用Socket来接受HTTP请求(想偷懒)
不知道 怎么弄 我弄的HTTP服务器 客户端WebClient调用说协议错误。。。。
求代码 求大神!!!

string reqest = @"GET /index.html HTTP/1.1";
            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            client.Connect(new IPEndPoint(IPAddress.Parse("61.135.169.105"), 80));
            client.Send(System.Text.Encoding.UTF8.GetBytes(reqest));
            byte[] data = new byte[655350];
            int length = client.Receive(data);
            Console.WriteLine(System.Text.Encoding.UTF8.GetString(data, 0, length));
            Console.ReadLine();

为什么 百度服务器 不响应我啊
------解决方案--------------------
用 Fillder2 抓一下浏览器的包,然后再看看自己发的 http request,就知道错在什么地方了。
------解决方案--------------------
你用fiddler看看ie发的数据,有很多header要发送的
  
*****************************************************************************
签名档: http://feiyun0112.cnblogs.com/
------解决方案--------------------
我完全没搞懂你要实现什么...

虽然说http最下面 也是tcp/ip.. 网站虽然也是80端口

但是那是http啊  你不能直接拿tcp/ip直接连吧..
------解决方案--------------------
google
HttpListener

------解决方案--------------------
看到是同簇的就给你我05年就用的Socket写的HttpRequest 

public class MyWebRequest
{
public MyWebRequest(Uri uri)
{
this._RequestUri=uri;
this._Referer="";
this._UserAgent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.1.4322)";
this._Cookie="";
this._AcceptType="*/*";
this._Method = "GET";
this._Timeout=15;
}




private void IniHeader()
{

this._Headers["Host"] = _RequestUri.Host;

if(this._Referer!="")
this._Headers["Referer"] = this.Referer;

if(this._UserAgent!="")
_Headers["User-Agent"] = this.UserAgent;

if(this._Cookie!="")
this._Headers["Cookie"] =this._Cookie;

this._Headers["Connection"] = "Keep-Alive";
}


public static MyWebRequest Create(string Url)
{
Uri uri=new Uri(Url);
return Create(uri);
}


public static MyWebRequest Create(Uri uri)
{
return new MyWebRequest(uri);
}


public MyWebResponse GetResponse()
{
this.IniHeader();
if(this._response == null 
------解决方案--------------------
 this._response.Socket == null 
------解决方案--------------------
 this._response.Socket.Connected == false)
{
this._response = new MyWebResponse();
this._response.Connect(this);
this._response.SetTime