multithreading - Python Print while waiting for input -
def receivedata(self): while true: data = self.soc.recv(1024) if data != "" or data != '' or data != "": sys.stdout.write("recv>> ") sys.stdout.write(data) sys.stdout.flush() if data == "server shutdown": self.soc.close() elif not data: continue def senddata(self): while true: try: sys.stdout.write("send>> ") msg = sys.stdin.readline() self.soc.send(msg) except socket.error: sys.stdout.write("socket connection timed out")
this part of client code of python, , expect while waits user input, prints receives server.
however, client not print when waiting user input -- prints when has been entered user.
is there way change prints when waiting user input?
if program needs wait on 2 separate events (user input , incoming socket data), you'll have use threads, like:
recv_thread = threading.thread(target=receivedata) recv_thread.setdaemon(true) recv_thread.start() senddata()
couple of things code:
- when
socket.error
encountered can other timeout. - at 1 point need exit
while
loop senddata (when user input text? or) in case of exception. - also add exception handling in receivedata
if
statement in receivedata not ok. replace to:if data: ...if statements...
Comments
Post a Comment