www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How do I use Socket.select?

reply Anonymouse <asdf asdf.net> writes:
I've been using blocking Sockets with timeouts for a while now, 
but wherever I look the word is "do consider using a non-blocking 
socket". Even the docs for std.socket.setOption;

 In a typical application, you might also want to consider using 
 a non-blocking socket instead of setting a timeout on a 
 blocking one.
So I'm trying to wrap my head around select but I can't get it to work in any way that's better than my current blocking reads. A SocketSet is a bundle of Sockets that you can add to and remove from, but you can't index. They're just there but out of reach. A call to Socket.select(SocketSet readers, SocketSet writers, SocketSet error) *blocks* (unless supplied a timeout), and when something happens returns a number telling you how many sockets changed status, but not which. The Sockets of those three SocketSets now magically disassociated themselves if they weren't one of those that changed status. You then have to call {readers,writers,error}.isSet(mySocket) and manually delve which one is still in there, and by extension, which one did change. But a "status change" for a reading Socket is "stuff can now connect", for a writing one "connection established", and not sure about the error ones. It doesn't seem to be "there's data waiting to be read" which I'd hoped for, since my program (IRC bot) in essence connects once and stays such throughout its life. What else is there to select that I'm missing? Or is it mostly a thing for programs with lots of Sockets, lots of connections?
Nov 12 2017
parent Mike Parker <aldacron gmail.com> writes:
On Sunday, 12 November 2017 at 21:45:56 UTC, Anonymouse wrote:

 But a "status change" for a reading Socket is "stuff can now 
 connect", for a writing one "connection established", and not 
 sure about the error ones. It doesn't seem to be "there's data 
 waiting to be read" which I'd hoped for, since my program (IRC 
 bot) in essence connects once and stays such throughout its 
 life.

 What else is there to select that I'm missing? Or is it mostly 
 a thing for programs with lots of Sockets, lots of connections?
The read set is used to determine if a socket has data waiting to read. It just happens that with a listening socket, that means there's a new connection. With a normal socket, it means data packets are ready. Maybe you should take a look at the classic Beej's guide, which covers the C API. Should be easy to translate to the std.socket API. http://beej.us/guide/bgnet/
Nov 12 2017