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 is part of my client code of python, and what I expect from this is while this waits for user input, it prints what it receives from server.
However, client does not print anything when it is waiting for user input — it only prints when something has been entered by user.
Is there a way that I could change this so that it prints even when it is waiting for user input?
If your program needs to wait on 2 separate events (user input and incoming socket data), you'll have to use threads, something like:
recv_thread = threading.Thread(target=receivedata)
recv_thread.setDaemon(True)
recv_thread.start()
senddata()
Couple of things about the code:
socket.error
is encountered it can be something other than timeout.while
loop from senddata (when the user input a certain text? or) in case of exception.if
statement in receivedata is not OK. you could replace it to:
if data:
...if statements...