Last active
July 8, 2020 08:05
-
-
Save yingshaoxo/8e0a5eb5b06d43546877adbfa3a5e834 to your computer and use it in GitHub Desktop.
asyncio TCP server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
class EchoServerClientProtocol(asyncio.Protocol): | |
def connection_made(self, transport): | |
self.transport = transport | |
self.peername = transport.get_extra_info('peername') | |
print('Connection from {}'.format(self.peername)) | |
def data_received(self, 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('Lost connection of {}'.format(self.peername)) | |
self.transport.close() | |
loop = asyncio.get_event_loop() | |
# Each client connection will create a new protocol instance | |
coro = loop.create_server(EchoServerClientProtocol, '127.0.0.1', 8888) | |
server = loop.run_until_complete(coro) | |
# Serve requests until Ctrl+C is pressed | |
print('Serving on {}'.format(server.sockets[0].getsockname())) | |
try: | |
loop.run_forever() | |
except KeyboardInterrupt: | |
pass | |
# Close the server | |
server.close() | |
loop.run_until_complete(server.wait_closed()) | |
loop.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment