Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

c# - Using Webclient ontop of already created TCP Socket

I need to communicate via a HTTP-Rest interface with a device. I cannot create a connection to this device actively. This device is creating a TCP-Socket with my program. So, I am listening on a port for this device. After the Socket is created, I need to send HTTP-Requests to this device on top of that socket. I Am acting as HTTP-Client and the device is acting as HTTP-Server. I cannot use WebClient for that as it creates its own TCP-Socket. But the socket as I said is already created. My fist question would be: Is there still a way to use WebClient or another alternative to create the HTTP-Requests and read out the Responses?

If I cannot use Webclient I need to implement it by myself. I saw that it is possible to use WebClient to create HTTP Header Bytes:

void SendHTTPRequest(string message)
{
  //create Header Bytes
  WebClient web = new WebClient();
  web.Headers.Set(HttpRequestHeader.Connection, "keep-alive");
  web.Headers.Set(HttpRequestHeader.Accept, "*/*");
  web.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate, br");

  //Built list with request bytes
  List<byte> bytesToSend = new List<byte>();
  bytesToSend.AddRange(Encoding.ASCII.GetBytes(message));
  bytesToSend.AddRange(web.Headers.ToByteArray());

  //Send request to the device
  WriteBytes(bytesToSend.ToArray());
}

My Second Question would be: Is there a way to decode the HTTP-Headers out of the received bytes from the response? So that I only need to implement the write and read methods for the HTTP-Body.

question from:https://stackoverflow.com/questions/66063985/using-webclient-ontop-of-already-created-tcp-socket

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...