Skip to content

Instantly share code, notes, and snippets.

@pedrominicz
Last active April 19, 2023 20:53
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save pedrominicz/b699dec01b4afd38b8aba83f3089e175 to your computer and use it in GitHub Desktop.
Save pedrominicz/b699dec01b4afd38b8aba83f3089e175 to your computer and use it in GitHub Desktop.
Extremely simple "distributed echo server" server in Python (Telnet clients should be able to connect to it).
#!/usr/bin/env python3
import socket
# Read "distributed echo server" as "(distributed echo) server". The "server"
# is not "distributed" but the echos are "distributed" to every connected
# client.
# Connect to the server with `telnet localhost 5000`.
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setblocking(False)
server.bind(('localhost', 5000))
server.listen(5)
connections = []
while True:
try:
connection, address = server.accept()
connection.setblocking(False)
connections.append(connection)
except BlockingIOError:
pass
for connection in connections:
try:
message = connection.recv(4096)
except BlockingIOError:
continue
for connection in connections:
connection.send(message)
@pucgenie
Copy link

This isn't Telnet, this is an Echo server (plus distribution of messages to all connected clients).

@pedrominicz
Copy link
Author

This isn't Telnet, this is an Echo server (plus distribution of messages to all connected clients).

Fair enough. I'll update the description.

@QGB
Copy link

QGB commented Oct 5, 2022

Session stopped
- Press to exit tab
- Press R to restart session
- Press S to save terminal output to file

Network error: Connection refused

@QGB
Copy link

QGB commented Oct 5, 2022

telnet.exe 127.0.0.1 5000
Trying 127.0.0.1...                     
                                                                                                                          
telnet: Unable to connect to remote host: Connection refused                

@pedrominicz
Copy link
Author

@QGB you are trying to connect to localhost but the script was binding your host name. I changed it to bind to localhost, so telnet localhost 5000 should work as expected.

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