Search code examples
c#httptcpclient

Sending data with HTTP and TcpClient not completely sent


What I'm trying to do is sending data with HTTP protocol with TcpClient. But i faced a problem here. The data i sent (after the headers) was not completely sent to the client's app (eg. browsers). Code:

// Building data.
string notfound = "NOT FOUND";
byte[] data = Encoding.UTF8.GetBytes(notfound);

// Building header.
m_responseBuilder.Append("HTTP/1.1 404 Not Found").Append(CRLF);
m_responseBuilder.Append("Server: ETP").Append(CRLF);
m_responseBuilder.Append("Content-Type: text/plain").Append(CRLF);
m_responseBuilder.Append("Content-Length: ").Append(data.Length.ToString()).Append(CRLF);
m_responseBuilder.Append(CRLF);
byte[] header = Encoding.UTF8.GetBytes(m_responseBuilder.ToString());

// Sending header.
await SendDataAsync(header);

// Sending data.
await SendDataAsync(data);

The SendDataAsync:

async Task SendDataAsync(byte[] data)
    {
        try
        {
            await m_tcpchannel.WriteAsync(data, 0, data.Length);
        }
        catch
        {
            DestroyConnection();
        }
    }

What I got:

NOT FOUN

Whats wrong right here?


Solution

  • Yeah, i got the problem. It was the CRLF. I wrote it \n\r instead of \r\n....