Roman Kozlov
Roman Kozlov

Reputation: 43

Python socket recv in thread

Here is my problem. I have a server on lua which sends data via socket. Data go constantly - it is a stream of exchange transactions. My python script as client should receive data.

def listen():

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = socket.gethostname()
    sock.connect(("localhost", 1111))

    with BytesIO() as response_bytes:
            while True:    
                try:
                    fragment = sock.recv(8196)    
                    print("Фрагмент: {}".format(fragment))
                except Exception:
                    pass

if __name__ == "__main__":

    t2 = threading.Thread(listen())
    t2.start()

    while True:

        print ("test") 

Main thread wait sock.recv(8196) line. I want that data from a socket were accepted in parallel, and the main stream continued to work. The current code blocks performance of main until listen is executed. I am not familiar with multiple tasks in Python. What decisions can be?

Upvotes: 0

Views: 3547

Answers (1)

Barmar
Barmar

Reputation: 782564

You have to pass the listen function to threading.Thread(). You're calling the function in the main thread, waiting for it to finish, and then passing its return value (which is just None, since the function never returns anything).

t2 = threading.Thread(target = listen)

Upvotes: 1

Related Questions