There are a number of ways to setup a client connection. The easiest way is using the with statement, giving you a nice looking construct:
>>> from net.client import TCP
>>> with TCP('localhost', 1234, collect=True) as client:
... for line in client:
... print line
...
This gives you a net.proto.basic.LineReceiver protocol instance which automatically connects to the given host and address.
You can also use the classes in a more traditional way, keep in mind that you have to initiate the connection yourself:
>>> from net.client import TCP
>>> client = TCP('localhost', 1234, collect=True)
>>> client.connect()
>>> for line in client:
... print line
...
When writing clients that need no concurrency of any kind, you can leave the client auto-detect when to stop and start the async core. If you wish to have more control over the async core’s behaviour, you can also start and stop the core manually.
You can start a threaded (async) core using the True parameter:
>>> from net.async import stop, start
>>> start(True)
Or you can use a blocking core:
>>> start(False)
You can stop the core any time you want and resume its operations later, the client connections will be kept open as they are not managed by the async core:
>>> stop()
All the net.proto.Proto instances export one or more callbacks you can use. For example the net.proto.basic.LineReceiver class:
>>> from net.client import TCP
>>> def print_line(line):
... print line
... return line
...
>>> smtp = TCP('localhost', 25, collect=True)
>>> smtp.onLine.addCallback(print_line)
>>> smtp.connect()
220 localhost ESMTP Ready
It is important to understand that callbacks can also modify data in the callback chain. If for example one argument line is passed to the callback, make sure you return line, or all callbacks that follow will break if they expect a single argument.
Also, you can provide some default arguments when creating callbacks. This can be handy to provide additional paramters to the callback:
>>> from net.client import TCP
>>> def print_connect(instance=None):
... if instance:
... print 'connected to %r' % (instance.peer)
...
>>> def print_line(line, prefix=''):
>>> print prefix, line
>>> return line
...
>>> smtp = TCP('localhost', 25, collect=True)
>>> smtp.onConnect.addCallback(print_connect, instance=smtp)
>>> smtp.onLine.addCallback(print_line, prefix='server:')
>>> smtp.connect()
connected to <Address host=localhost ip=IPv6(::1) port=25>
server: 220 localhost ESMTP Ready
In this example we didn’t return the keyword arguments. This is because the default arguments and keyword arguments will be supplied to this specific callback only. All the other callbacks can have their own arguments and keyword arguments.