Skip to content

Instantly share code, notes, and snippets.

@arseniyturin
Created December 8, 2021 21:36
Show Gist options
  • Save arseniyturin/2c75bf60ab1f1279159a18a2f6cac248 to your computer and use it in GitHub Desktop.
Save arseniyturin/2c75bf60ab1f1279159a18a2f6cac248 to your computer and use it in GitHub Desktop.
'''
Basic Python Threaded TCP Server
--------------------------------
socketserver.TCPServer requires only two things:
- Address (host, port)
- Handler class to process requests
Must be derived from `BaseRequestHandler` or `StreamRequestHandler`
'''
from socketserver import TCPServer
from socketserver import ThreadingMixIn
from socketserver import BaseRequestHandler
class Handler(BaseRequestHandler):
# Overwrite handle method to process request
def handle(self):
# In simple case we hope request will fit in 4096 bytes
request = self.request.recv(4096)
# Bare minimum HTTP-response
response = (
'HTTP/1.1 200 OK\r\n'
'Content-Type: text/html; charset=UTF-8\r\n\r\n'
'<h1>It Works!</h1>'
).encode()
# Sending back to the client
self.request.send(response)
# We can make our server threaded by subclassing ThreadingMixIn
class Server(ThreadingMixIn, TCPServer):
allow_reuse_address = True
daemon_threads = True
try:
server = Server(('', 8000), Handler)
server.serve_forever()
except KeyboardInterrupt:
server.shutdown()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment