I want a socket server implementation with the Python asyncio library. I have this code but I don't know if it's correct. I want to implement SSL, too.
I used code from the documentation example and I added some modifications for it the way I want. Now the code works with any client implementation with the socket library, and I added a UNIX signal handler, too.
import asyncio
import functools
import os
import signal
class ServerClientProtocol(asyncio.Protocol):
def __init__(self):
self.peername = ""
def connection_made(self, transport):
self.peername = transport.get_extra_info('peername')
print('Connection from {}'.format(self.peername))
self.transport = transport
def data_received(self, data):
print("dato: ", data)
message = data.decode()
print('Data received: {!r}'.format(message))
print('Send: {!r}'.format(message))
self.transport.write(data)
def connection_lost(self, exc):
print('Close {0} socket. Exception: {1}'.format(self.peername, exc))
self.transport.close()
def ask_exit(signame):
print("SeƱal {} recibida: Salir".format(signame))
server.wait_closed()
loop.stop()
loop = asyncio.get_event_loop()
for signame in ('SIGINT','SIGTERM'):
loop.add_signal_handler(getattr(signal, signame),
functools.partial(ask_exit,signame))
# Each client connection will create a new protocol instance
coro = loop.create_server(ServerClientProtocol, '127.0.0.1', 12345)
server = loop.run_until_complete(coro)
# Serve requests until CTRL+c is pressed
print('Serving on {}'.format(server.sockets[0].getsockname()))
print("pid {}: send SIGINT or SIGTERM to exit.".format(os.getpid()))
try:
loop.run_forever()
except KeyboardInterrupt:
pass
finally:
loop.close()
I want opinions about this code, please.