简体   繁体   English

在python中异步接收TCP数据包

[英]Asynchronous receiving TCP packets in python

I have an instant messaging app, with client written in python. 我有一个即时通讯应用程序,客户端用python编写。

Code that connects to a server: 连接到服务器的代码:

def connect(self, host, port, name):
    host = str(host)
    port = int(port)
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, port))
    s.send('CONNECT:' + name)
    print s.recv(1024)

    return s

Then s will be stored in a self.socket. 然后s将存储在self.socket中。

Here is function that receives tcp packets from server and prints it to command line. 这是从服务器接收tcp数据包并将其打印到命令行的函数。

def chat(self):
    while True:
        data = self.socket.recv(4096)
        if not data:
            pass
        else:
            print data

So in my mind it should receive everything server sends and prints out, but it isn't happens. 因此,在我看来,它应该接收服务器发送并打印出的所有内容,但不会发生。 Anyone knows how to bring it to life? 有人知道如何将其变为现实吗?

There is a way with select function to monitor multiple streams, make a list of all the streams you need to handle and use the select function for it, for the user input use sys.stdin and all the sockets that you expect to chat with. 使用select函数可以监视多个流,列出需要处理的所有流并为其使用select函数,对于用户输入,请使用sys.stdin和您希望与之聊天的所有套接字。
check this: https://docs.python.org/2/library/select.html 检查一下: https : //docs.python.org/2/library/select.html
But still the best way to do asynchronous chat will be with udp , it will work really fine 但是,仍然最好的异步聊天方式是使用udp ,它确实可以正常工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM