import socket
listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.bind(('127.0.0.1', 0))
listen_socket.getsockname()
('127.0.0.1', 54805)
listen_socket.listen(1)
accept waits until a connection is established from the other side (a .connect()
call)
connection, address = listen_socket.accept()
recv waits until there is data to recv from the connection (e.g. a .send
)
request = connection.recv(1024)
print(request.decode())
HTTP/1.1 GET /somepage
Now we can send the reply and close the connection because we are done
connection.sendall(b"""HTTP/1.1 200 OK
Content-type: text/html
<html>
<body>
<h1> hello, world </h1>
</body>
</html>
""")
connection.close()
Wrapping this all in a single function that handles a complete request
def handle_request(sock):
connection, address = sock.accept()
request = connection.recv(1024)
print(request.decode())
connection.sendall(b"""HTTP/1.1 200 OK
Content-type: text/html
<html>
<body>
<h1> hello, world </h1>
</body>
</html>
""")
connection.close()
handle_request(listen_socket)
GET / HTTP/1.1 Host: 127.0.0.1:54805 Cookie: _xsrf=2|2c3b26c1|3a353a3e15e26f29dc2989f4176dd739|1537274238; username-127-0-0-1-62692="2|1:0|10:1537274238|24:username-127-0-0-1-62692|44:MGQzYWVmYjg1YTdiNDgwMmJiMmNjMTlhNjUzODM3N2M=|d2790faa1308b5c019da742cb16d1bceadf3175d59cc4001d1a4cdcbf2f57da0"; _ga=GA1.1.1413211555.1475583612 Connection: keep-alive Upgrade-Insecure-Requests: 1 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Safari/605.1.15 Accept-Language: en-us DNT: 1 Accept-Encoding: gzip, deflate