Skip to content

Instantly share code, notes, and snippets.

@Aareon
Forked from jacobian/unicorn-socketserver.py
Last active December 13, 2018 19:07
Show Gist options
  • Save Aareon/0d4790f14385ab0574c935fe515d4491 to your computer and use it in GitHub Desktop.
Save Aareon/0d4790f14385ab0574c935fe515d4491 to your computer and use it in GitHub Desktop.
A simple preforking echo server using SocketServer.
import os
import socketserver
"""
Simple forking echo server built with Python's SocketServer library. A more
Pythonic version of http://gist.github.com/203520, which itself was inspired
by http://tomayko.com/writings/unicorn-is-unix.
"""
class EchoHandler(socketserver.StreamRequestHandler):
def handle(self):
self.wfile.write(f"Child {os.getpid()} echo>")
self.wfile.flush()
message = self.rfile.readline()
self.wfile.write(message)
print(fr"Child {os.getpid()} echo'd: {message}")
if __name__ == '__main__':
server = socketserver.ForkingTCPServer(('localhost', 4242), EchoHandler)
print("Server listening on localhost:4242...")
try:
server.serve_forever()
except KeyboardInterrupt:
print("\nbailing...")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment