0

I need to send a lot of text data via TcpClient. Similar solution found here

Code:

string data = "test";
byte[] dataBytes = Encoding.UTF8.GetBytes(data);

byte[] compressed = Compress(dataBytes);
int dataLength = compressed.Length;

string headers =
    "HTTP/1.1 200 OK\r\n"
    + "content-type: text/plain;charset=utf-8\r\n"
    + "connection: keep-alive\r\n"
    + "content-encoding: gzip\r\n"
    + $"content-length: {dataLength}\r\n"
    + "\r\n";

byte[] headerBytes = Encoding.UTF8.GetBytes(headers);

using (NetworkStream ns = client.GetStream())
{
    ns.Write(headerBytes, 0, headerBytes.Length);
    ns.Write(compressed, 0, dataLength);
}

byte[] Compress(byte[] raw)
{
    using (MemoryStream ms = new MemoryStream())
    using (GZipStream gzip = new GZipStream(ms, CompressionMode.Compress, true))
    {
        gzip.Write(raw, 0, raw.Length);
        return ms.ToArray();
    }
}

The browser does not receive data except for headers. Any help is appreciated.


UPDATE

Here is correct compression method:

byte[] Compress(byte[] raw)
{
    using (MemoryStream ms = new MemoryStream())
    {
        using (GZipStream gzip = new GZipStream(ms, CompressionMode.Compress, true))
        {
            gzip.Write(raw, 0, raw.Length);
        }

        return ms.ToArray();
    }
}
shmnff
  • 647
  • 2
  • 15
  • 31
  • 1
    You have to close the `GZipStream` object before you return the compressed bytes, otherwise the data written to it isn't completely flushed (and if the data is small enough, _no_ data would be written). See marked duplicate. Also, why are you reinventing the wheel? You should be using `HttpClient` to interact with HTTP servers. – Peter Duniho Nov 01 '19 at 05:21
  • @PeterDuniho this is the server. thank you for help – shmnff Nov 01 '19 at 05:38
  • _"this is the server"_ -- okay, that answers why you're not using `HttpClient`. But the same basic question remains: why aren't you using features built into the .NET eco-system to provide HTTP server functionality, without having to reimplement that functionality from scratch? E.g. ASP.NET, Angular, Blazor, etc.? – Peter Duniho Nov 01 '19 at 05:50

0 Answers0