Skip to content

Instantly share code, notes, and snippets.

@KrisMelikova
Last active April 11, 2023 06:37
Show Gist options
  • Save KrisMelikova/32c6d30075c6b9c030c88b9e90f67cf8 to your computer and use it in GitHub Desktop.
Save KrisMelikova/32c6d30075c6b9c030c88b9e90f67cf8 to your computer and use it in GitHub Desktop.
A simple echo server
import selectors
import socket
from selectors import SelectorKey
from typing import List, Tuple
selector = selectors.DefaultSelector()
server_socket = socket.socket()
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_address = ('127.0.0.1', 8080)
server_socket.setblocking(False)
server_socket.bind(server_address)
server_socket.listen()
selector.register(server_socket, selectors.EVENT_READ)
while True:
events: List[Tuple[SelectorKey, int]] = selector.select(timeout=1)
if len(events) == 0:
print('Событий нет, подожду еще!')
for event, _ in events:
event_socket = event.fileobj
if event_socket == server_socket:
connection, address = server_socket.accept()
connection.setblocking(False)
print(f"Получен запрос на подключение от {address}")
selector.register(connection, selectors.EVENT_READ)
else:
data = event_socket.recv(1024)
print(f"Получены данные: {data}")
event_socket.send(data)
@KrisMelikova
Copy link
Author

Try it:
telnet localhost 8080

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