Created
October 15, 2023 07:57
-
-
Save jpcofr/3273c1555f733e08c112b63cc89c47d9 to your computer and use it in GitHub Desktop.
This script serves a JSON payload in multiple chunks, demonstrating HTTP/1.1 chunked transfer encoding.
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
""" | |
This script implements a basic HTTP server that listens on port 8080 and responds to | |
incoming HTTP requests with chunked transfer encoding as per the HTTP/1.1 standard. | |
Upon receiving a request, the server sends a JSON payload as the response, broken | |
down into a specified number of chunks to demonstrate the chunked transfer | |
encoding mechanism. | |
""" | |
# HTTP 1 - Server | |
import socket | |
import time | |
import json | |
response_data = json.dumps({ | |
"name": "Raymond Springer", | |
"age": 30, | |
"married": True, | |
"children": [ | |
{"name": "Jane Springer", "age": 10}, | |
{"name": "Peter Springer", "age": 8} | |
] | |
}).encode('utf-8') | |
def send_chunked_response(client_socket, chunk_size): | |
fragments = [response_data[i:i + chunk_size] | |
for i in range(0, len(response_data), chunk_size)] | |
for fragment in fragments: | |
# Send chunk size in hex followed by CRLF | |
chunk_size_header = f"{len(fragment):X}\r\n".encode() | |
print(f"Sending fragment: {fragment}") | |
client_socket.send(chunk_size_header + fragment + b'\r\n') # Send chunk data followed by CRLF | |
# Send end of chunks | |
client_socket.send(b'0\r\n\r\n') | |
def handle(client_socket): | |
request = client_socket.recv(1024) | |
desired_num_chunks = 3 # Set your desired number of chunks | |
total_size = len(response_data) | |
chunk_size = total_size // desired_num_chunks # Determine the chunk size | |
if request: | |
client_socket.send( | |
b'HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nTransfer-Encoding: chunked\r\n\r\n') | |
send_chunked_response(client_socket, chunk_size) | |
client_socket.close() | |
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
sock.bind(('0.0.0.0', 8080)) | |
sock.listen(5) | |
while True: | |
client_sock, addr = sock.accept() | |
handle(client_sock) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment