Asynchronous receiving TCP packets in python
<p>I have an instant messaging app, with client written in python.</p>

<p>Code that connects to a server:</p>

<pre><code>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
</code></pre>

<p>Then s will be stored in a self.socket.</p>

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

<pre><code>def chat(self):
    while True:
        data = self.socket.recv(4096)
        if not data:
            pass
        else:
            print data
</code></pre>

<p>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?</p>

<p>There is a way with <code>select</code> function to monitor multiple streams, make a list of all the streams you need to handle and use the <code>select</code> function for it, for the user input use <code>sys.stdin</code> and all the sockets that you expect to chat with.<br>
check this: <a href="https://docs.python.org/2/library/select.html" rel="nofollow">https://docs.python.org/2/library/select.html</a><br>But still the best way to do asynchronous chat will be with <code>udp</code>, it will work really fine</p>

python sockets tcp