I have a client.py and a server.py. The client receives occasional messages from the server. The client can also send messages to the server.
Because raw_input appears to block the main thread, when the client receives a message from the server, it can't print to the console, and requires raw_input to finish first.
I've tried to use multithreading to get around this, but in the following code, the raw_input doesn't even get called. The following is client.py
import socket
import sys
import threading
BUFFER_SIZE = 1024
def listen_for_server_response(s):
while 1:
data = s.recv(BUFFER_SIZE)
print(data)
def main():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((sys.argv[1], int(sys.argv[2])))
thread = threading.Thread(target = listen_for_server_response(s))
thread.start()
while 1:
command = raw_input("Command: ")
s.send(command)
if __name__ == "__main__":
main()
Any help on this is much appreciated!
this seems like bad design but you need to call threading with a callable function
thread = threading.Thread(target = listen_for_server_response,args=(s,))
thread.start()
by calling it like you do in the example you are calling it before the thread starts and just looping forever ... you dont even make it to thread.start