Skip to content

Instantly share code, notes, and snippets.

@rustyeddy
Created June 13, 2019 14:29
Show Gist options
  • Save rustyeddy/b52a4df5438518ac4c245af8c5fc4288 to your computer and use it in GitHub Desktop.
Save rustyeddy/b52a4df5438518ac4c245af8c5fc4288 to your computer and use it in GitHub Desktop.
Echo Server in Python
import socket
def server(host, port):
sock = socket.socket()
sock.bind((host, port))
sock.listen(2)
print(f'Server up and listening on {host} {port}')
try:
while True:
conn, cliaddr = sock.accept()
# Replace echo with something interesting
echo(conn, cliaddr)
finally:
sock.close()
def echo(conn, cliaddr):
file = conn.makefile()
print(f'Received connection from {cliaddr}')
try:
while True:
line = file.readline()
if not line:
print(f'Failed to get a line, try again')
continue
line = line.rstrip()
if line == 'quit':
conn.sendall(b'closing connection\r\n')
break
print(f'{cliaddr} -> {line}')
conn.sendall(b'Echoed: %a\r\n' % line)
finally:
print(f'Closing up shop {cliaddr} quit')
file.close()
conn.close()
if __name__ == '__main__':
server('0.0.0.0', 8080)
@rustyeddy
Copy link
Author

This is a simple TCP echo server in python. Replace the echo function with something more interesting and wrap it in a thread or process.

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