Search code examples
c#network-programmingasp.net-core-mvctcpclientnetworkstream

How to: TcpClient NetworkStream Lifecycle


I have a ASP.NET CORE MVC web application that needs to communicate with a TcpServer for certain tasks. I have a class on the Web application that manages the requests to this TcpServer.

My Tcp client class contains a method called Request(string message) that is meant to be used by my ASP.Net web application to call to the TcpServer and returns the TcpServer's response. The method goes like so:

public string Request(string message)
{
    // Open stream and client.
    TcpClient client = new TcpClient(this._ipAddr, this._port);
    NetworkStream stream = client.GetStream();

    // Write to stream
    Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
    stream.Write(data, 0, data.Length);

    // Read from stream to get response. Read 256 bytes at a time so
    // as not to overload the system in case requests are ginormous.
    Byte[p] data = new Byte[256];
    string responseData = "";
    int bytesRead;
    while ( (bytesRead = stream.Read(data, 0, 256)) > 0)
    {
        responseData += System.Text.Encoding.ASCII.GetString(data, 0, bytesRead);
    }

    // Close stream and client
    stream.Close();
    client.Close();

    return responseData;
}

Note that I call this method many times in the application. So I am constantly newing up (And therefor connecting) and closing both the TcpClient and NetworkStream.

I've looked at the MSDN docs and on stack overflow. All the examples I see only send one single request. That doesn't really help me as I will be sending request many times throughout the lifetime of the web application. It's going to be a very frequent request. I want to understand how to manage this.

I am bran new to TCP servers and clients. What is the proper lifecycle? What is the proper way to use a TcpClient and NetworkStream?

To be more specific, should I be newing up and closing the TcpClient on each request? Or should the TcpClient be a singleton that is open throughout the lifetime of my web app... In which case I assume the stream is what I should be opening and closing for each request.


Solution

  • You do not need to open and close your socket frequently, just open it once and close it when you want to stop talking with that TCP server, but you need amend your TCP server by defining a pattern which indicates the end of the response, so when you read that pattern you know the response is done.

    Regarding performance issues, this returns to your usage of that connection, if you are sure that your channel is secure and you have a plenty of resources then definitely it is better to keep it opened. However; if you do not use it frequently then it is OK to open and close it each time.