I am using python asynchat to implement a network protocol.
At connection time I need to send a command and the server answer with a session.
My main problem is that I need to wait until I get the session response. but not sure how to implement this. should I use socket.recv for the connection setup? is a good idea?
When writing a network application using asynchronous techniques, you wait by recording your state somewhere and then letting the main loop continue. At some future time, the data you’re waiting for will become available, the main loop will notify you of that fact, and you can combine the new data with the recorded state to complete whatever task you are working on. Depending on the specific task, you may need to go through this cycle many times before your task is actually done.
These ideas are basically the same regardless of what asynchronous system you’re using. However, Twisted is a vastly superior system to asynchat, so I’m not going to try to explain any of the asynchat details. Instead, here’s an example that does the kind of thing you’re asking about, using Twisted:
To see how this behaves, you can launch a simple server (eg
nc -l 1234) and point the client at it. You’ll see the greeting arrive and you can send some bytes back. Once you’ve sent back 30, the client will print them (and then hang around indefinitely, because I implemented no further logic in that protocol).