Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Multi-threaded Python3 HTTP Server
#!/usr/bin/env python3
import sys, os, socket
from socketserver import ThreadingMixIn
from http.server import SimpleHTTPRequestHandler, HTTPServer
HOST = socket.gethostname()
class ThreadingSimpleServer(ThreadingMixIn, HTTPServer):
pass
'''
This sets the listening port, default port 8080
'''
if sys.argv[1:]:
PORT = int(sys.argv[1])
else:
PORT = 8080
'''
This sets the working directory of the HTTPServer, defaults to directory where script is executed.
'''
if sys.argv[2:]:
os.chdir(sys.argv[2])
CWD = sys.argv[2]
else:
CWD = os.getcwd()
server = ThreadingSimpleServer(('0.0.0.0', PORT), SimpleHTTPRequestHandler)
print("Serving HTTP traffic from", CWD, "on", HOST, "using port", PORT)
try:
while 1:
sys.stdout.flush()
server.handle_request()
except KeyboardInterrupt:
print("\nShutting down server per users request.")
@g10guang

This comment has been minimized.

Copy link

@g10guang g10guang commented Jul 27, 2018

@sbguy01

This comment has been minimized.

Copy link

@sbguy01 sbguy01 commented Oct 16, 2020

Does this multi-threaded server work on Windows Server?

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