Py学习  »  Python

线程中的python socket recv

Roman Kozlov • 4 年前 • 746 次点击  

这是我的问题。我在lua上有一个服务器,它通过socket发送数据。数据不断地移动——它是一个交换事务流。我的python脚本作为客户端应该接收数据。

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") 

主线程等待sock.recv(8196)行。我希望来自套接字的数据被并行接受,并且主流继续工作。当前代码阻止main的性能,直到执行listen。我不熟悉python中的多个任务。什么决定可以?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/47528
 
746 次点击  
文章 [ 1 ]  |  最新文章 4 年前
Barmar
Reply   •   1 楼
Barmar    5 年前

你必须通过 listen 函数到 threading.Thread() 是的。在主线程中调用函数,等待它完成,然后传递它的返回值(即 None ,因为函数从不返回任何内容)。

t2 = threading.Thread(target = listen)