Skip to content

Instantly share code, notes, and snippets.

@math2001
Created April 26, 2018 02:35
Show Gist options
  • Save math2001/163adb8367ae0b6b75c6876c7e8e91d3 to your computer and use it in GitHub Desktop.
Save math2001/163adb8367ae0b6b75c6876c7e8e91d3 to your computer and use it in GitHub Desktop.
Possibly the simplest version of a chat server made with Python
import asyncio
clients = {}
async def handle_new_client(reader, writer):
writer.write("Welcome to our server!\n".encode('utf-8'))
peername = '{}:{}'.format(*writer.get_extra_info("peername"))
clients[peername] = reader, writer
while True:
b = await reader.readline()
if not b:
del clients[peername]
return
for r, w in clients.values():
w.write("{}: {}".format(peername, b.decode('utf-8')).encode('utf-8'))
await w.drain()
loop = asyncio.get_event_loop()
server = loop.run_until_complete(asyncio.start_server(handle_new_client, "", 9877))
loop.run_forever()

You can build a client in Python if you feel like it, but you might as well just use telnet:

$ telnet localhost 9877
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment