Real Master
Real Master

Reputation: 347

Connection close if its idle for certain time

I have Client – Server application implemented in .Net 4.5, everything works Fine.

Multiple clients (Hardware devices) are connected to server concurrently and data transfer occurs.

Now I want to close the connection from server if no data transfer happens for certain time period on socket i.e. I simply want to close the connection from server, if it remains idle (No data transfer occurs ) for let’s say 5 Min.

Upvotes: 0

Views: 1343

Answers (3)

Bojan Komazec
Bojan Komazec

Reputation: 9526

You have to implement connection timeouts at the application level (as a part of your communication protocol): for each connection, after you receive data, start a timer set to predefined timeout value (e.g. 5 minutes). If you receive data before timeout, reset the timer. If you don't receive the data, stop the timer and close that connection.

Upvotes: 0

Claudio
Claudio

Reputation: 652

I think you can implement something like this:

DateTime startDateTime = DateTime.Now;

using (var client = new HttpClient)
{
    DateTime currentDateTime = DateTime.Now;
    while(currentDateTime - startDateTime < threshold)
    {
        currentDateTime = DateTime.Now;
        if(dataArrive)
        {
           startDateTime = DateTime.Now;
        }
    }

    //TO DO: Close communication channel
}

Where threshold is your 5 Min. and //dataArrive is true when data transfer occurs.

Instead, you do an http request you can use the HttpClient.Timeout property.

Upvotes: 1

You have explore the option to set proper value for idle_timeout parameter that takes care closing the connection once it reached the threshold.

Upvotes: 0

Related Questions