Skip to content

Instantly share code, notes, and snippets.

@imankulov
Last active December 7, 2021 06:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imankulov/70181bdd39e70e5679f6fc93fdc7f036 to your computer and use it in GitHub Desktop.
Save imankulov/70181bdd39e70e5679f6fc93fdc7f036 to your computer and use it in GitHub Desktop.
aio chat client and server examples

This is a simple implementation for TCP server and client. The server listens for the port 9090 of the localhost, receives messages from any connected clients, and sends them to all connected peers. The client is started with a username as an argument, reads in an infinite loop messages from the string, re-format them as "name > message\n" and send to the server. In a different async function it also waits for message from the server and prints the to the console.

Files:

  • aio_chat_client.py: client implementation
  • aio_chat_server.py: server implementation

Dependencies: Python 3.6+ and aioconsole

Install aioconsole

pip install aioconsole

Start server as this:

python ./aio_chat_server.py

Start two clients in separate consoles as

python ./aio_chat_server.py Foo

and

python ./aio_chat_server.py Bar

Try to write a message in any console.

More info:

import sys
import asyncio
from aioconsole import ainput, aprint
writer = None
my_name = sys.argv[1]
async def main():
await asyncio.gather(network(), console())
async def network():
global writer
reader, writer = await asyncio.open_connection('127.0.0.1', 9090)
while not reader.at_eof():
data = await reader.readline()
await aprint(data.decode('utf-8'), end='')
writer.close()
async def console():
while True:
message = await ainput('')
formatted = f'{my_name} > {message}\n'
if writer:
writer.write(formatted.encode('utf-8'))
await writer.drain()
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
import asyncio
# Global list of clients. Each of those clients is a "writer" object, which
# we will use to send message to peers
clients = []
async def start_server():
"""
Async function to start the server
"""
await asyncio.start_server(handle_messages, '127.0.0.1', 9090)
async def handle_messages(reader, writer):
"""
The handler. Every time new client is connected to the server, a new
async handler is initiated with a (reader, writer) pair
"""
print('Someone connected')
# Add the client to the list
clients.append(writer)
# Asynchronously read messages from the client until it
# closes the connection
while not reader.at_eof():
message = await reader.readline()
# send message to each of the peers
for writer in clients:
if not writer.is_closing():
writer.write(message)
await writer.drain()
print('Someone disconnected')
writer.close()
loop = asyncio.get_event_loop()
# start the server and wait while the connection is established
loop.run_until_complete(start_server())
# process incoming messages until Ctrl+C is pressed
loop.run_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment