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
According to the MSDN documentation there are three causes that return true for
Poll(microSeconds, SelectMode.SelectRead);
- if
Listen()
has been called and a connection is pending - If data is available for reading
- If the connection has been closed, reset, or terminated
Let's see if we can discriminate them:
- You always know if
Listen()
has been called before, so you don't need to consider that cause if you have not. - Ok, you go for that.
- 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:
needs not to be considered
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"
}
You could use Socket property Available. It returns how much data is available to read.
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.
You could use the select() system call on the underlying handle.
You can use Select() method instead of Poll(). Actually when looking into Socket.Poll with ILSpy (reflector tool) the internal code is calling select on the socket.
In addition, calling Poll() in a tight loop will increase memory allocation as it does a new IntPtr[] on each call. Calling Select() lets you reuse the arrays instead of allocating new ones under the hood.
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.
© 2022 - 2024 — McMap. All rights reserved.