简体   繁体   中英

How to send image as an HTTP response using TcpClient

In my job I have server and clients (several devices) connected in to the same network.

Clients contacts with server using their web-browser.

Server is running a C# program that uses TcpListener to receive requests from browsers.

I'm trying to send an image through TcpClient to client device but this is the result:

这是结果

I'v tried:

  • Read image file as String
  • Read image file as Byte[]

After some searches inside Chrome Developer console i found an error net::ERR_CONTENT_LENGTH_MISMATCH .

i don't know why Content-Length: length-in-byte value isn't correct even through new FileInfo(Target).Length .

Code I use:

TcpListener Listener = new TcpListener(local_address, 9090);
Listener.Start();

TcpClient client = Listener.AcceptTcpClient();
NetworkStream ns = client.GetStream();

string target = HeaderKeys.GetValue("target"); /* image file in the request*/ 
string mime_type = MimeType.Extract(target); /* mime-type of the file */

byte[] content = File.ReadAllBytes(target);

StreamWriter writer = new StreamWriter(ns);
// response header
writer.Write("HTTP/1.0 200 OK");
writer.Write(Environment.NewLine);
writer.Write($"Content-Type: {mime_type}");
writer.Write(Environment.NewLine);
writer.Write("Content-Length: " + content.Length);
writer.Write(Environment.NewLine);
writer.Write(Environment.NewLine);
writer.Write(content);
writer.Flush();
client.Close();

I'v tried

  • NetworkStream directly.
  • reading image file in MemoryStream and NetworkStream to write.
  • reading image file as byte[] and convert it to Base64.

The issue was because of StreamWriter

I've solved the issue using this code:

    TcpClient client = Listener.AcceptTcpClient();
    Stream s = client.GetStream();

    byte[] file_content = File.ReadAllBytes(file);

    StringBuilder header = new StringBuilder();

    header.Append("HTTP/1.1 200 OK\r\n");
    header.Append($"Content-Type: {mime_type}\r\n");
    header.Append($"Content-Length: {file_content .Length}\r\n\n");

    byte[] h = Encoding.ASCII.GetBytes(header.ToString());

    s.Write(content, 0, content.Length);
    s.Write(b, 0, b.Length);
    s.Flush();

    client.Close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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