Skip to content

Instantly share code, notes, and snippets.

@luabida
Last active February 11, 2023 18:58
Show Gist options
  • Save luabida/320442ebb0de0e074bec1d24988c9cc7 to your computer and use it in GitHub Desktop.
Save luabida/320442ebb0de0e074bec1d24988c9cc7 to your computer and use it in GitHub Desktop.
Smallest Python Webserver - by Dr. Charles Severance
from socket import *
def createServer():
serversocket = socket(AF_INET, SOCK_STREAM)
try:
serversocket.bind(('localhost',9000))
print('Starting server at http://127.0.0.1:9000/')
serversocket.listen(5)
while(1):
(clientsocket, address) = serversocket.accept()
rd = clientsocket.recv(5000).decode()
pieces = rd.split('\n')
if (len(pieces) > 0):
print(pieces[0])
data = 'HTTP/1.1 200 OK\r\n'
data += 'Content-Type: text/html; charset=utf-8\r\n'
data += '\r\n'
data += '<html><body>Hello World</body></html>\r\n\r\n'
clientsocket.sendall(data.encode())
clientsocket.shutdown(SHUT_WR)
except KeyboardInterrupt:
print('Shutting down...\n')
except Exception as e:
print(f'Error:\n {e}')
serversocket.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment