Question

I have a basic command-line chat client and server in Python, but this would be applicable to probably any language. I ran into a very obvious problem, and I'm not sure if there would be any way around it (aside from using a GUI! Which would quickly solve the problem). When the server sends a message to the client, causing the client to print() the message, it's inserted in the exact same place where the person would be typing their own message, causing it to be split by the incoming message. For example (written as # comments to avoid weird syntax highlighting):

# Client1: Knock-knock!
# Client2: Who's there?
# Client1: Interrupting cow!
# Client2: Inter
# Client1: MOOOOOOO
# Client2: rupting cow who?

Where Client2 hasn't hit enter since typing Who's there?.

So obviously, there's all sorts of workarounds like panels on a GUI, but I'm curious to know if there's anyway to implement this strictly in the native terminal/command prompt. I couldn't find anything remotely like this during my searching the internet for a solution! Thanks!

Was it helpful?

Solution

I'd use something like https://pypi.python.org/pypi/blessings/ which lets you set up a terminal with a cursor.

You can move the cursor "up" when you want to print output from the other connection and then move it back down when you want to get input.

If you want to get crazy you can do all that magic by yourself with terminal control commands (on windows you'll need colorama) which will let you do things like:

print("\033[6;3HHello")

Which moves the cursor to x,y. This requires an ansi terminal.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top