HTTP 客户端到 TCP 服务器 (C#)

HTTP Client to TCP Server (C#)

我没有收到 HTTPClient 编辑的 post 内容,但我可以阅读其他信息,例如 Content-Length 和其他 header。让我在这里解释一下代码:

这是服务器代码:

 TcpListener tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"),1234);
tcpListener.Start()//Start the listener and wait for client to connect.
while(true)
{
 TcpClient newclient = tcpListener.AcceptTcpClient(); // calls the readdata everytime a post is put in the specified URL - done by client below.
 ReadData(newClient)
}

public void ReadData(TcpClient newclient)
{
            byte[] buffer = new byte[50];
            Stream ns = newclient.GetStream();     
            ns.Read(buffer, 0, buffer.Length);
            Console.WriteLine( Encoding.UTF8.GetString(buffer));
 }
Sample Server Output :


 Received JSON DATA POST /MovieData HTTP/1.1
Host: 127.0.0.1:3291
Content-Length: 48
Expect: 100-continue
Connection: Keep-Alive - But the Content is missing. I am not sure why. I tried to extend the buffer size but still Content Length and other info is posted but content is missing. 

这是客户端代码: 客户端不断发送消息“循环发送请求

                    HttpClient ModifyClient = new HttpClient();
                    ModifyClient.BaseAddress = new Uri("http://127.0.0.1:1234/MovieData");
                    while(true)
                   {                        
    
                    ModifyClient.PostAsync(ModifyClient.BaseAddress
                                   , new StringContent("SendingRequest",Encoding.UTF8));
                   }

我能够收到服务器中显示的 post 消息,每个 post 但缺少的是实际发送“SendingRequest”文本的字符串内容。其他 header 属性在那里。 我在使用 HttpClient 时缺少某些配置吗?

试试这个

using System.Net;

var client = new HttpClient()
{
    DefaultRequestVersion =  HttpVersion.Version30,
    DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact
};

Console.WriteLine("--- Localhost:5001 ---");
HttpResponseMessage resp = await client.GetAsync("https://localhost:5001/");
string body = await resp.Content.ReadAsStringAsync();
Console.WriteLine(
    $"status: {resp.StatusCode}, version: {resp.Version}, " +
    $"body: {body.Substring(0, Math.Min(100, body.Length))}");

参考:microsoft

或:this

最终参考:socket-example

您的服务器存在几个问题: 缺少分号:

tcpListener.Start()//Start the listener and wait for client to connect.

newclient 与 newClient 和 ReadData() 后缺少分号

TcpClient newclient = tcpListener.AcceptTcpClient(); // calls the readdata everytime a post is put in the specified URL - done by client below.
            ReadData(newClient)

第二个问题是,您正在使用 HTTPClient 连接到 TCP-Server,您应该使用 TCPClient 并发送一个 STREAM(这是您所期望的!)

         TcpClient client = new TcpClient("/127.0.0.1", 1234);
         string message = "myMessage";
         // Translate message into ASCII and store it as a Byte array
         Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);

         // Get a client stream for reading and writing.
         NetworkStream stream = client.GetStream();

         // Send the message to the connected TcpServer.
         stream.Write(data, 0, data.Length);