Skip to content

Instantly share code, notes, and snippets.

@JonCooperWorks
Created February 13, 2013 19:30
Show Gist options
  • Select an option

  • Save JonCooperWorks/4947389 to your computer and use it in GitHub Desktop.

Select an option

Save JonCooperWorks/4947389 to your computer and use it in GitHub Desktop.
threaded server in python
'''
620031587
Simple Python HTTP Server
'''
#import socket module
import socket
import threading
#Factor out common page serving logic to function
def serve(conn_socket, page):
try:
f = open(page)
status_code = '200 OK'
except IOError:
f = open('404.html')
status_code = '404'
finally:
with f:
content = f.read()
headers = 'HTTP/1.1 %s\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: %d\r\n\r\n' % (status_code, len(content))
#Send headers's
conn_socket.send(headers)
for char in content:
conn_socket.send(char)
conn_socket.close()
def get_connection(server_socket):
conn_socket, addr = server_socket.accept()
msg = conn_socket.recv(1024)
if msg is None:
return None
return conn_socket, msg.split()[1][1:]
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 9000
#Prepare a server socket
serverSocket.bind(('', port))
serverSocket.listen(1)
while True:
#Establish the connection
print 'Ready to serve...'
#Get the connection socket and filename
args = get_connection(serverSocket)
#No request sent. Stop server from crashing upon recv() timeout
if args is None:
continue
#Spawn a new thread to handle request. New connection object will be created at next iteration.
threading.Thread(target=serve, args=args).start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment