Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to poll a socket in C# only when something is available for reading?

I'm wondering whether there is a way to poll a socket in c# when only one of the conditions (data is available for reading) is satisfied, I'm aware of the socket.Poll method but this can return true if any number of the 3 conditions specified returns true as specified here: MSDN: Socket.Poll

like image 363
Dark Star1 Avatar asked Dec 08 '22 06:12

Dark Star1


2 Answers

According to the MSDN documentation there are three causes that return true for

Poll(microSeconds, SelectMode.SelectRead);

  1. if Listen() has been called and a connection is pending
  2. If data is available for reading
  3. If the connection has been closed, reset, or terminated

Let's see if we can discriminate them:

  1. You always know if Listen() has been called before, so you don't need to consider that cause if you have not.
  2. Ok, you go for that.
  3. Means that you can not stay in the Poll() call and need to find out what really happened. One option is to check the socket's state immediately after Poll() returned.

Conclusion:

  1. needs not to be considered

  2. and 3. can be handled by checking the socket state each time true is returned.

So I would go for (untested):

if (s.Poll(microSeconds, SelectMode.SelectRead)))
{
  if (!s.Connected)
    // Something bad has happened, shut down
  else
    // There is data waiting to be read"
}
like image 101
Armin Avatar answered Dec 09 '22 19:12

Armin


You could use Socket property Available. It returns how much data is available to read.

like image 25
Agg Avatar answered Dec 09 '22 19:12

Agg