【发布时间】:2019-11-06 18:03:50
【问题描述】:
我正在尝试使用套接字制作HTTP request。我的代码如下:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class test
{
public static void Main(String[] args)
{
string hostName = "127.0.0.1";
int hostPort = 9887;
int response = 0;
IPAddress host = IPAddress.Parse(hostName);
IPEndPoint hostep = new IPEndPoint(host, hostPort);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Connect(hostep);
string request_url = "http://127.0.0.1/register?id=application/vnd-fullphat.test&title=My%20Test%20App";
response = sock.Send(Encoding.UTF8.GetBytes(request_url));
response = sock.Send(Encoding.UTF8.GetBytes("\r\n"));
bytes = sock.Receive(bytesReceived, bytesReceived.Length, 0);
page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes);
Console.WriteLine(page);
sock.Close();
}
}
现在,当我执行上面的代码时,什么都没有发生,而当我在浏览器中输入我的 request_url 时,我收到来自 Snarl 的通知,说 Application Registered 并且我从浏览器得到的响应是
SNP/2.0/0/OK/556
我从我的代码中得到的响应是SNP/3.0/107/BadPacket。
那么,我的代码有什么问题。
【问题讨论】:
-
您是否有理由需要使用 Sockets 而不是
System.Net.Http.HttpClient? -
或 Webclient 就这点...
-
不,没有具体原因。其实我不知道
HttpCLient or Webclient。但无论如何,我想了解我上面的代码有什么问题。 -
发送主url后是否需要额外发送“\r\n”?如果您不使用浏览器发送它,请尝试在代码中将其删除,以便复制与您的浏览器完全相同的行为。
-
另外,正如 jgauffin 所说,您必须包含内容长度、主机等。如果您不想这样做,请使用高级对象发送,例如 HttpWebRequest。