|
I think what messes with people with select() is the slightly itchy way you have to specify the file descriptors to watch. It's not really as tough as it looks, but you do have other options.
One 'soft option' which is OK for simple programs is to poll using non-blocking IO. You can use blocking IO for the send(), but investigate setsockopt() and set recv() to non-blocking; in cases where there's nothing to read you'll get an error return from recv(). Just make sure you don't end up thrashing, repeatedly polling without any delay between checks.
Using signal-driven IO is also often easier than using select() where your application is nice and simple. Not sure how that translates to Windows, though; I suspect it doesn't.
Quite early on, MJordan2nd suggested threads ... weirdly, this is actually one of the easiest and most intuitive methods. Threads are separate lightweight processes within a single process, and allow your program to do more than one thing at a time. The way you can do this sort of chat program with threads is just create one that always reads the socket and prints everything it receives, and another that always reads the terminal and writes whatever it finds to the socket. The two of them don't need to interact (though you can occasionally get in a bit of a mess on the terminal if you don't do any synchronisation between the two), so this is dead easy; when one is blocking on recv() the other is still free to read from the user.
You do have to learn how to use threads to do it this way, but that'll be useful down the line anyway so I recommend it.
|