问题
I'm writing a multithreaded socket chat. Is there any way to get the console input at a given time before the user has hit enter?
Let's say I'm typing a message, and while I'm typing it, the server sends a message to me. The server's message will get printed right after the message I'm currently writing.
How it looks:
Me>Hey!
Server>Heya!
Me>How are yServer>Hello!
If possible, I want to save the "How are y" string, remove it and paste it again after the server output:
Me>Hey!
Server>Heya!
Server>Hello!
Me>How are y
回答1:
your problems boils down to two separate issues. number one is reading input from stdin or console character by character. this is tricky by itself, since most common approaches to reading input only do entire lines.
the second issues you're facing is going back and forth on the screenm because you have to update the current input and the new incoming messages this is quite possible, but the way to do it depends heavily on your terminal type and it's capabilities:
http://unix.stackexchange.com/questions/43945/whats-the-difference-between-various-term-variables
doing this correctly for all possible $TERM values on all OSs is rather tricky as well. you might do better using a library such as jcurses:
https://github.com/sunhong/jcurses
that abstracts this away from you.
来源:https://stackoverflow.com/questions/34912232/read-current-console-input-before-enter