Created
June 13, 2019 14:29
-
-
Save rustyeddy/b52a4df5438518ac4c245af8c5fc4288 to your computer and use it in GitHub Desktop.
Echo Server in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.