Created
October 23, 2018 20:16
-
-
Save Snawoot/9f32bd2b551e78cf4506c3de49dc54f1 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python3 | |
import asyncio | |
import socket | |
async def handle_echo(reader, writer): | |
addr = writer.get_extra_info('peername') | |
while True: | |
data = await reader.read(4096) | |
if not data: | |
break | |
message = data.decode() | |
print("Received %r from %r" % (message, addr)) | |
print("Send: %r to %r" % (message, addr)) | |
writer.write(data) | |
await writer.drain() | |
print("Client %r disconnected" % (addr,)) | |
writer.close() | |
if __name__ == '__main__': | |
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) | |
sock.bind(('', 8888)) | |
loop = asyncio.get_event_loop() | |
coro = asyncio.start_server(handle_echo, sock=sock, loop=loop) | |
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