views:

942

answers:

5

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

A: 

Found something in class NetworkStream. Property NetworkStream.DataAvailable returns true if data is available for reading. Object of networkstream is returned dealing with TcpListener and TcpClient. This is one abstraction level higher than socket.

I found no way to come from Socket to NetworkStream. A NetworkStream is using a socket and is the stream representation of a socket. But I dont know what the networkstream is doing there with the socket.

Christian13467
A: 

You could use the select() system call on the underlying handle.

Joshua
My first thought too, but not shure if this is what dark-star really means.
Christian13467
A: 

true if Listen has been called and a connection is pending; -or- true if data is available for reading; -or- true if the connection has been closed, reset, or terminated; otherwise, returns false.

I understand that you want to check if the second option is the one returning true? After checking if the Poll returns true, you can check if the connection is open, that means; not connection, closed, reset or terminated.

If it is open, then it's the second option return true.

Phoexo
Dark Star1
I would assume that, yes.
Phoexo
+2  A: 

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

Agg
+1  A: 

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 assume 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 find out details if this really happened, you may 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";
}
Armin
Thank you all for your response.
Dark Star1