Last active
October 20, 2021 07:11
-
-
Save markusdosch/d907f94abf198758f0b9061086b9362f to your computer and use it in GitHub Desktop.
Minimal Python Webserver
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
# 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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For responding with HTTP (minimal example), replace the line
client.sendall(...)
with:Notes
b
=> bytes literal (see https://www.studytonight.com/post/significance-of-prefix-b-in-a-string-in-python for more)"""
notation in Python, youy need to make sure every line does not contain leading whitespace (this whitespace will end up in the string!).