'HTTP Client to TCP Server (C#)
I am not receiving the Content posted by the HTTPClient but I can read the other information such as Content-Length and other headers. Let me explain the code here:
Here is the Server Code :
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.
Here is the Client Code : Client keeps sending message "Sending Request in a loop
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));
}
I am able to receive the post message as shown in the server for every post but what is missing is that is the string content that is actually sent "SendingRequest" text. The other header properties are there. Is it some configuration that I am missing while using the HttpClient ?
Solution 1:[1]
try this
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))}");
refrence : microsoft
or : this
final refrence : socket-example
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mohammad asadi |
