Skip to content

Instantly share code, notes, and snippets.

@Ari24-cb24
Created March 31, 2022 16:01
Show Gist options
  • Save Ari24-cb24/1ac2f698ae77ea8ce330db7d03e3d569 to your computer and use it in GitHub Desktop.
Save Ari24-cb24/1ac2f698ae77ea8ce330db7d03e3d569 to your computer and use it in GitHub Desktop.
A python webserver (experimental)
import time
import socket
OUTPUT = '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Hello World!</title></head><body>Hello World!</body></html>'
class WebServer:
def __init__(self, connection):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind(connection)
@staticmethod
def __read_data(conn):
part = b""
while True:
data = conn.recv(1)
part += data
if part.endswith(b"\r\n"):
break
return part
def listen(self):
self.socket.listen()
conn, addr = self.socket.accept()
print("Received connection from " + str(addr))
# data = self.__read_data(conn)
# self.handle(data)
conn.send(b"HTTP/1.1 200 OK\r\n")
conn.send(b"Server: HTTPython\r\n")
conn.send(b"Content-Type: text/html\r\n")
conn.send(b"Connection: Closed\r\n")
conn.send(b"\r\n")
conn.send(b"<h1>Hello from HTTPython</h1>\n")
conn.send(b"<h2>yes</h2>")
conn.close()
def handle(self, data):
print(data)
if __name__ == '__main__':
HOST, PORT = "localhost", 9999
web_server = WebServer((HOST, PORT))
web_server.listen()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment