Search code examples
c#tcplistener

TcpListener parser


I have a simple TcpListener and I want to parse the data it receives. Here is what I have and it works:

TcpListener listener = new TcpListener(localAddr, port);
var client = listener.AcceptTcpClient();
var buffer = new byte[10240];
var stream = client.GetStream();
var length = stream.Read(buffer, 0, buffer.Length);
var incomingMessage = Encoding.UTF8.GetString(buffer, 0, length);

results

Incoming message: POST /api/v1/myapi/ HTTP/1.1
Content-Type: application/json
ApiKey: dac38055e7914b1f8ca5de1683b58322
cache-control: no-cache
Postman-Token: 50da88e4-5c89-4368-a5eb-1574eb35b24a
User-Agent: PostmanRuntime/7.6.1
Accept: */*
Host: MyDNS:13000
accept-encoding: gzip, deflate
content-length: 590
Connection: keep-alive

AmazingDataFromBody

Is there anything that will parse this or do I have to write my own?


Solution

  • As i can see, you want to handle an HTTP Request, so:

    1. Instead of TCPListener use HttpListener to handle HTTP Request and Response. Link: https://learn.microsoft.com/en-us/dotnet/api/system.net.httplistener?view=netframework-4.7.2
    2. Add the Prefix to HTTPLister with your URI http:localhost[:port]/api/v1/myapi/, using the host and port.
    3. Start the HttpListener.
    4. Use GetContext() to get the HttpListenerRequest object.
    5. With HttpListenerRequest you can get the Headers and body, check this link: https://learn.microsoft.com/en-us/dotnet/api/system.net.httplistenerrequest?view=netframework-4.7.2
    6. Use GetContext() to get the HttpListenerResponse object.

    Using the sample of https://learn.microsoft.com/en-us/dotnet/api/system.net.httplistener?view=netframework-4.7.2 you can see:

        // This example requires the System and System.Net namespaces.
        public static void SimpleListenerExample(string[] prefixes)
        {
            // 1
            HttpListener listener = new HttpListener();
            // 2
            listener.Prefixes.Add("http:/localhost:8080//api/v1/myapi/");
    
            // 3
            listener.Start();
            Console.WriteLine("Listening...");
    
            //4
            HttpListenerContext context = listener.GetContext();
            HttpListenerRequest request = context.Request;
    
            //5
            HttpListenerResponse response = context.Response;
    
            //Building a response
            string responseString = "<HTML><BODY>My response</BODY></HTML>";
            //Take care of encoding
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
    
            //6
            response.ContentLength64 = buffer.Length;
            //Get the stream to wite the response body
            System.IO.Stream output = response.OutputStream;
            output.Write(buffer,0,buffer.Length);
            // You must close the output stream.
            output.Close();
            listener.Stop();
        }
    

    if you don't want to use HttpListener you can use these basic steps, using TCPListener and TCPClient but you must have knowledge about HTTP Protocol:

    1. Read the Header, line by line.
    2. Valid if there is Body, using the the content-length header.
    3. Read the body, according information of the size of content-length.

    In my case, i prefer use HttpListener, which allows handle several aspect of HTTP, like certified.