简体   繁体   English

用C#编写“原始” HTTP客户端

[英]Writing a “raw” HTTP client in C#

I am trying to write a "raw" HTTP client in C#. 我试图用C#编写“原始” HTTP客户端。 You may ask why?? 您可能会问为什么?

My aim is to implement an HTTP client in J2ME (which can only do GET and limited POST), but first I need to understand the HTTP protocol better (hence the C# attempt). 我的目标是在J2ME中实现HTTP客户端(只能执行GET和有限的POST),但是首先我需要更好地理解HTTP协议(因此需要进行C#尝试)。

My first attempts are failing: 我的第一次尝试失败了:

var requestBytes = Encoding.UTF8.GetBytes(@"GET / HTTP/1.1
User-Agent: CSharp
Host: www.google.com

");
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect("www.google.com", 80);
socket.Send(requestBytes);
var responseBytes = new byte[socket.ReceiveBufferSize];
socket.Receive(responseBytes);
Console.Out.Write(Encoding.UTF8.GetString(responseBytes));

The socket opens, but then blocks at the Receive call. 套接字打开,但是在接收调用时阻塞。 After a couple of seconds the remote host closes the connection. 几秒钟后,远程主机将关闭连接。

Any ideas? 有任何想法吗?

The same happens when I try to connect using the RAW mode in puTTY. 当我尝试在PuTTY中使用RAW模式进行连接时,也会发生相同的情况。

It might be best if you're testing this thing, to install IIS or Apache locally and then use the address 127.0.0.1; 如果正在测试此东西,最好是在本地安装IIS或Apache,然后使用地址127.0.0.1;这可能是最好的。 it gives you more scope to test different things! 它给您更多的范围来测试不同的东西!

Being a bit of a prude, I wouldn't like it if somebody used my website to test their implementation of the HTTP protocol. 有点傲慢,如果有人使用我的网站来测试其HTTP协议的实现,我将不喜欢它。

If you're going to be playing down at the "raw" level, then you're responsible for understanding the protocols down there. 如果您要淡化“原始”级别,那么您有责任了解那里的协议。 See Hypertext Transfer Protocol -- HTTP/1.1 . 请参阅超文本传输​​协议-HTTP / 1.1

Otherwise, you should just stick to the WebRequest and WebClient classes. 否则,您应该坚持使用WebRequest和WebClient类。

I think you need to use TcpListener class. 我认为您需要使用TcpListener类。

// Begin listening for incoming connection requests
TcpListener myListener = new TcpListener("localhost", 8080); // change to yours
myListener.Start();

Then 然后

Socket mySocket = myListener.AcceptSocket();
if (mySocket.Connected)
{
   // do some work
   mySocket.Send(<data>, <length>, 0);
}

Hope it will help. 希望它会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM