Documentation for pulsar 0.9.2. For development docs, go here.
This example illustrates how to write a simple TCP Echo server and client pair.
The example is simple because the client and server protocols are symmetrical
and therefore the EchoProtocol
will also be used as based class for
EchoServerProtocol
.
The code for this example is located in the examples.echo.manage
module.
To run the server:
python manage.py
Open a new shell, in this directory, launch python and type:
>>> from manage import Echo
>>> echo = Echo(('localhost',8060))
>>> echo(b'Hello!')
b'Hello!'
The first step is to write a small class handling a connection
pool with the remote server. The Echo
class does just that,
it subclass the handy AbstractClient
and uses
the asynchronous Pool
of connections as backbone.
The second step is the implementation of the EchoProtocol
,
a subclass of ProtocolConsumer
.
The EchoProtocol
is needed for two reasons:
start_request()
method.data_received()
method.examples.echo.manage.
EchoProtocol
(loop=None, one_time_events=None, many_times_events=None)[source]¶An echo ProtocolConsumer
for client and servers.
The only difference between client and server is the implementation
of the response()
method.
separator
= '\r\n\r\n'¶A separator for messages.
buffer
= ''¶The buffer for long messages
data_received
(data)[source]¶Implements the data_received()
method.
It simply search for the separator
and, if found, it invokes
the response()
method with the value of the message.
start_request
()[source]¶Override start_request()
to write
the message ended by the separator
into the transport.
response
(data)[source]¶Clients return the message so that the
ProtocolConsumer.on_finished
is called back with the
message value, while servers sends the message back to the client.
examples.echo.manage.
EchoServerProtocol
(loop=None, one_time_events=None, many_times_events=None)[source]¶The EchoProtocol
used by the echo server()
.
response
(data)[source]¶Override response()
method by writing the
data
received back to the client.
examples.echo.manage.
Echo
(address, full_response=False, pool_size=10, loop=None)[source]¶A client for the echo server.
Parameters: |
|
---|
_loop
¶The event loop used by the client IO requests.
The event loop is stored at this attribute so that asynchronous
method decorators such as task()
can be used.
address
¶remote server TCP address.
full_response
¶Flag indicating if the callable method should return the
EchoProtocol
handling the request (True
) or
the server response message (False
).
Default: False
examples.echo.manage.
server
(name=None, description=None, **kwargs)[source]¶Create the SocketServer
with EchoServerProtocol
as protocol factory.