I want to refresh the screen every one second. I'm implementing a chat with ncurses.
So far, I have the following function:
void print_chat(char *chat) {
mvprintw(1, 1, "RPC Chat");
move(2, 1);
for (int i=0; i<CHAT_WIDTH; i ) {
addch('_');
}
move(CHAT_HEIGHT 3, 1);
for (int i=0; i<CHAT_WIDTH; i ) {
addch('_');
}
mvprintw(CHAT_HEIGHT 5, 1, "Enter message: ");
}
Which prints the following screen:
In the main function I'd like to have a loop that refreshes the screen every 1 second, obtaining possible new messages from a server, and refreshes the screen in that interval so if any, new messages could be displayed. I also want to read users input while the refreshing goes on at the same time. Do I need threads?
My attempt so far in the main function:
while (1) {
print_chat(chat);
refresh();
sleep(1);
chat = read_chat_from_server();
/*char l = getch(); --> This would block the loop, waiting for input...
}
Do I need threads to achieve this? If so, would the thread be able to reprint the screen? Any other way to solve this problem?
CodePudding user response:
The problem is that getch()
is waiting for the user to press return.
You want to have a look at raw()
and call it once before getting any input. By calling this function you can get characters from the user without him pressing return, pausing your program. Basically the console reads user input, prints each character as its being written, and when the user sends '\n'
, it returns that input to your program (See this answer).
You might want to look at noecho()
too. Similar to raw()
, lets you scan for user input (using getch()
) without printing the characters on the screen. This is usually useful for letting your program handle how the characters are displayed.
Finally, it may be a good idea to call refresh()
when something gets updated (e.g. check each second if you got a message, you sent one, etc.) and then call refresh()
.
CodePudding user response:
You need to call the timeout()
function when you first initialize your program.
timeout(0)
should cause getch()
to not wait for user input.