2011-10-17 5 views
3

HTTP 요청을 보내고 C# 소켓을 통해 서버에서 응답을 보내려고합니다.이 언어는 새로운 것입니다.C# 소켓을 통한 HTTP

나는 다음 코드 (IP가 올바르게 해결) 쓴 것 : 내가 잘못 뭐하는 거지

IPEndPoint RHost = new IPEndPoint(IP, Port); 
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
socket.Connect(RHost); 

String HTTPRequestHeaders_String = "GET ?q=fdgdfg HTTP/1.0 
Host: google.com 
Keep-Alive: 300 
Connection: Keep-Alive 
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.205 Safari/534.16 
Referer: http://google.com/"; 

MessageBox.Show(HTTPRequestHeaders_String, "Request"); 

byte[] HTTPRequestHeaders = System.Text.Encoding.ASCII.GetBytes(HTTPRequestHeaders_String); 
socket.Send(HTTPRequestHeaders, SocketFlags.None); 

String Response = ""; 
byte[] buffer = new byte[(int) socket.ReceiveBufferSize]; 

int bytes; 
do 
{ 
    // On this lane program stops to react 
    bytes = socket.Receive(buffer); 
    // This line cannot be reached, tested with breakpoint 
    Response += Encoding.ASCII.GetString(buffer, 0, bytes); 
} 
while (bytes >= 0); 

MessageBox.Show(Response, "Response"); 

? 난 그냥 페이지의 전체 HTML을로드하거나 응답에서 적어도 몇 문자가 필요합니다 (난 can not do this).

+3

사용'HttpWebRequest' 클래스를. – SLaks

+2

@SLaks 'WebClient' ... –

+1

문자열로 HTTP 요청 헤더를 생성해야합니다.이 클래스에서 가능합니까? –

답변

5

나는 것이 원시 수행하려는 경우 프로토콜 자체에 찾고, http://www.w3.org/Protocols/HTTP/1.0/spec.html#Request

을 제안하고 요청을 종료 할 CRLF를 보내보십시오;

+0

와우, 나는이 문제에 5 시간 같이이고 요청을 종료하는 것을 잊었다, 다량 감사합니다! :) –

+0

자, 문제가 해결되었습니다. 처음부터 Http 헤더를 작성하는 방법을 배웠습니다. 더 높은 수준의 추상화로 전환 할시기입니다. 앞서 언급했듯이,'HttpWebRequest' 또는'WebClient'를 사용하십시오. –

0

한 손에 수있는 TcpClient 클래스가있다) (요청 본문을 문자열로 생성하는) 요청을 완전히 제어 할 수 있어야하며, 반면에 저수준 소켓보다 사용하는 것이 훨씬 쉽습니다.

1
var webClient = new WebClient(); 
webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); 
Stream responseStream = webClient.OpenRead("http://www.google.com"); 
if (responseStream != null) 
{ 
    var responseReader = new StreamReader(responseStream); 
    string response = responseReader.ReadToEnd(); 
    MessageBox.Show(response); 
}