Fireship Fireship - 1 month ago 5x
Python Question

Asynchronous receiving TCP packets in python

I have an instant messaging app, with client written in 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.

Here is function that receives tcp packets from server and prints it to command line.

def chat(self):
while True:
data = self.socket.recv(4096)
if not data:
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?


The thing is as a socket sends a message it expects a return message from the other side, That seems to be the only reason for that.
however 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.
check this:
But still the best way to do asynchronous chat will be with udp, it will work really fine