Search code examples
c#imagehttp-headerstcpclienttcplistener

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 TcpClientto client device but this is the result:

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.

Solution

  • 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();