asyncio for UNIX socket
Pavlos Parissis
pavlos.parissis at gmail.com
Wed Dec 16 20:16:11 EST 2015
Hi,
I am trying to write UNIX socket client which sends 1 cmd
and saves the received data to a file.
Based on what I found on documentation I came up with::
import asyncio
class UnixProtocol(asyncio.Protocol):
def __init__(self, loop):
self.cmd = 'show stat\n'
self.loop = loop
self.data = []
def connection_made(self, transport):
transport.write(self.cmd.encode())
print('Data sent: {!r}'.format(self.message))
def data_received(self, data):
print('Data received: {!r}'.format(data))
self.data.append(data.decode())
def connection_lost(self, exc):
print('The server closed the connection')
print('Stop the event loop')
if self.data:
with open('/tmp/somedata', 'w') as fp:
fp.writelines(self.data)
self.loop.stop()
loop = asyncio.get_event_loop()
s_file = '/run/haproxy/admin1.sock'
coro = loop.create_unix_connection(lambda: UnixProtocol(loop), s_file)
loop.run_until_complete(coro)
loop.run_forever()
loop.close()
I am not sure if the above is the proper way to do the job.
Am I doing the right thing to write the data to the file when peer
closes the connection?
Thanks,
Pavlos
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 819 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20151217/b7a3bcd5/attachment.sig>
More information about the Python-list
mailing list