I'm currently trying to make a small tcp chat application. Sending and receiving messages already works fine... But the problem is:
When i start typing a message while i receive one... it appears after the text I'm writing
[User sent > "hello", then I started writing "i am writing..." then user wrote " i sent a..." before i sent my message... so it has been placed after my input...
I want the incoming message always to be before my input !
this is my current code:
con = connect.User()
server = raw_input("Type in the server adress \n[leave blank to use xyr.no-ip.info]\n>:")
while nick == "":
nick = raw_input("Type in your nickname\n>:")
msg = raw_input()
if msg == "q":
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if server == "":
msg_in = sock.recv(1024)
if not str(msg_in).startswith("[py]" + nick):
elif str(msg_in).startswith("/u "):
if nick == "":
nick = "guest"
print("Name changed to ""guest""")
thread.start_new_thread(receiver, (server, ))
def connect(self, server="xyr.no-ip.info", nick="guest"):
nickel = nick
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if server == "":
print("server changed to xyr.no-ip.info")
self.sock.send("[py]" + nick + "\n")
self.sock.send(nick + " connected with a python client\n")
print("registered as " + nick)
def send(self, msg):
self.sock.send(msg + "\n")
Your code writes everything to stdout. Whenever something arrives to either of your sender/receiver threads, it prints to stdout. The issue with that is, due to the fundamental nature of output streams, you cannot accomplish the following :
Things happen strictly in the order of occurrence. The moment something comes in, wherever the cursor is, the print statement dumps that data over there. You cannot modify that behaviour without using fancier / more powerful constructs.
In order to do what you want, I would use ncurses. You seem to be using python on Windows, so you're going to have to do some digging on how to get equivalent functionality. Check out this thread : Curses alternative for windows