Skip to content

Instantly share code, notes, and snippets.

@markusdosch
Last active October 20, 2021 07:11
Show Gist options
  • Save markusdosch/d907f94abf198758f0b9061086b9362f to your computer and use it in GitHub Desktop.
Save markusdosch/d907f94abf198758f0b9061086b9362f to your computer and use it in GitHub Desktop.
Minimal Python Webserver
"""
# Minimal Python Webserver (adopted from https://de.wikipedia.org/wiki/Socket_(Software)#Server)
## Notes
- It does not close the socket on exit (e.g. on interrupt) => it may take some time until the OS releases the port for reuse.
- It does not speak HTTP yet - you need to implement it yourself.
- It does not read the full client request, just the first 1024 bytes. Then, it sends its answer. When implementing HTTP, you need to first read all headers (=> until you receive `\r\n\r\n` = blank line). Using the headers, you need to identify whether a message body will follow. In the easiest case (other cases are out of scope for here), a `Content-Length` header signalizes how many bytes of message body will follow. With this number, you know how many bytes you need to read to receive the full request.
- Don't name the file `socket.py`. This will result in a (Python-specific) error.
"""
import socket
host = "127.0.0.1" # IP adress of the server
port = 5000 # Port used by the server
s = socket.socket()
s.bind((host, port))
s.listen()
while True:
client, addr = s.accept()
print(f"Connected to {addr}")
data = client.recv(1024)
if not data:
client.close()
print(f"Received from client: {data.decode()}")
client.sendall(data)
client.close()
@markusdosch
Copy link
Author

For responding with HTTP (minimal example), replace the line client.sendall(...) with:

    client.sendall(b"""HTTP/1.1 200 OK

""")

Notes

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