I am writing socket server program. which will listen to the particular IP and Port. once the data come in it process the data and store it in the database. I want my program to listen 24*7 whether data comes in or not. if comes then process it otherwise wait until new client joins
Here is the sample code
static async Task AcceptClientsAsync(TcpListener listener, CancellationToken ct)
{
try
{
var clientCounter = 0;
while (!ct.IsCancellationRequested)
{
TcpClient client = await listener.AcceptTcpClientAsync().ConfigureAwait(true);
clientCounter++;
EchoAsync(client, clientCounter, ct);
}
}
catch (Exception e)
{
NewLog.WriteErrorLogToBuffer("exception in AcceptClientsAsync " + e.InnerException, false);
}
}
it is working fine but I'm getting out of memory exception after some time. is there any way to solve this?
Your TcpClient
instances are never disposed, so they will remain open until your program goes out of memory and closed by the OS.
You need to close the TcpClient
after you finished using it. The best way to do this is by wrapping it inside a using
block:
using(TcpClient client = await listener.AcceptTcpClientAsync().ConfigureAwait(true))
{
clientCounter++;
EchoAsync(client, clientCounter, ct);
}
An alternative is to manually closing it using its Close()
method, but be aware that if an exception is thrown before the call to Close()
your TcpClient
will remain open forever.