giambio/tests/server.py

55 lines
2.0 KiB
Python
Raw Normal View History

2020-03-19 19:48:24 +01:00
import giambio
from giambio.socket import AsyncSocket
2020-03-19 19:48:24 +01:00
import socket
import logging
import sys
2020-11-16 08:07:19 +01:00
import traceback
2020-03-19 19:48:24 +01:00
2020-11-14 10:42:46 +01:00
# A test to check for asynchronous I/O
2020-03-19 19:48:24 +01:00
2020-11-14 12:59:58 +01:00
async def serve(address: tuple):
2020-03-19 19:48:24 +01:00
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(address)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.listen(5)
asock = giambio.wrap_socket(sock) # We make the socket an async socket
2020-11-14 12:59:58 +01:00
logging.info(f"Serving asynchronously at {address[0]}:{address[1]}")
2020-11-16 08:07:19 +01:00
async with giambio.create_pool() as pool:
conn, addr = await asock.accept()
logging.info(f"{addr[0]}:{addr[1]} connected")
pool.spawn(handler, conn, addr)
2020-06-17 16:23:43 +02:00
2020-03-19 19:48:24 +01:00
2020-11-14 12:59:58 +01:00
async def handler(sock: AsyncSocket, addr: tuple):
addr = f"{addr[0]}:{addr[1]}"
2020-11-12 23:25:51 +01:00
async with sock:
await sock.send_all(b"Welcome to the server pal, feel free to send me something!\n")
2020-03-19 19:48:24 +01:00
while True:
await sock.send_all(b"-> ")
data = await sock.receive(1024)
2020-03-19 19:48:24 +01:00
if not data:
break
elif data == b"raise\n":
await sock.send_all(b"I'm dead dude\n")
raise TypeError("Oh, no, I'm gonna die!")
2020-03-19 19:48:24 +01:00
to_send_back = data
2020-07-13 22:02:31 +02:00
data = data.decode("utf-8").encode("unicode_escape")
2020-03-19 19:48:24 +01:00
logging.info(f"Got: '{data.decode('utf-8')}' from {addr}")
await sock.send_all(b"Got: " + to_send_back)
logging.info(f"Echoed back '{data.decode('utf-8')}' to {addr}")
logging.info(f"Connection from {addr} closed")
if __name__ == "__main__":
2020-11-14 12:59:58 +01:00
port = int(sys.argv[1]) if len(sys.argv) > 1 else 1500
logging.basicConfig(level=20, format="[%(levelname)s] %(asctime)s %(message)s", datefmt="%d/%m/%Y %p")
try:
2020-11-14 12:59:58 +01:00
giambio.run(serve, ("localhost", port))
2020-11-14 10:42:46 +01:00
except (Exception, KeyboardInterrupt) as error: # Exceptions propagate!
2020-11-14 12:59:58 +01:00
if isinstance(error, KeyboardInterrupt):
logging.info("Ctrl+C detected, exiting")
else:
logging.error(f"Exiting due to a {type(error).__name__}: {error}")