Sobes.tech
Junior — Middle

Have you had experience working with the HTTP protocol over sockets?

sobes.tech AI

Answer from AI

Yes, experience with the HTTP protocol via sockets in Python involves using the socket module to create a TCP connection and manually send HTTP requests and handle responses. This is useful for understanding the low-level workings of HTTP without using high-level libraries.

Example of a simple HTTP GET request via sockets:

import socket

host = 'example.com'
port = 80

request = f"GET / HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n"

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((host, port))
    s.sendall(request.encode())
    response = b''
    while True:
        data = s.recv(4096)
        if not data:
            break
        response += data

print(response.decode())

This approach allows you to independently parse HTTP headers and the response body, which is useful for a deep understanding of the protocol.