With the help of some friends, I’m writing a MUD. Step one: learn network programming. To that end, I’m writing a chat client and server, which will eventually be used as a jumping off point for the MUD engine and clients. The engine is done, and it works. I can telnet to it from multiple windows, and when one window types something, all the other windows see it. So, the communication isn’t a problem.
The problem is, I’m using the curses library (well, ncurses, really) to control the formatting, rather than just telnetting in. My idea is to run an infinite loop, waiting for the server to send something to the client, at which point the screen is refreshed with the new message. I can’t figure out how to get text from the user, though, to send to the server. I was trying variations on:
for (;;) {
if (getstr(text)) { foo(); }
else { bar(); }
}
Which fails, presumably because it’s waiting for getstr() to return something. A deja search yielded a few “Sorry, can’t do that in C/C++” replies. Does anyone have any idea how I can do this? I sure would appreciate it.
Of course, that should be
for (;;) {
I think what you’re asking is how to check for keyboard input without waiting (i.e. how to do a “nonblocking read”). Your program fragment will read a line typed in by the user (ending with the newline) but will wait until the line is typed. If you want to simultaneously see what the person on the other end is typing, you need to do a nonblocking read. You can do this with curses [which is not part of standard C/C++; the responses you saw were probably from one of the comp.lang.c groups], but you can’t use getstr(). You need to put the terminal in either raw or cbreak mode (“man raw” or “man cbreak” for details) and then use getch(), which will return immediately with either a single character (if the user has typed one) or ERR (if he hasn’t).
A non-blocking read is exactly what I want, but I didn’t know if that was common terminology, or specific to socket programming. I figured it would be something to do with (n)curses, but I’ve only learned the very basics necessary to scroll lines up the screen so far. Thanks, I’ll look into raw, cbreak, and getch().
You can also use select() in a polling loop to determine whether there are characters ready to read from stdin; in fact, you can use the same select() call to poll both the socket and the terminal.