#!/usr/bin/env python # coding: utf-8 # In[1]: import socket listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listen_socket.bind(('127.0.0.1', 0)) listen_socket.getsockname() # In[3]: listen_socket.listen(1) # accept waits until a connection is established from the other side (a `.connect()` call) # In[20]: connection, address = listen_socket.accept() # recv waits until there is data to recv from the connection (e.g. a `.send`) # In[21]: request = connection.recv(1024) # In[18]: print(request.decode()) # Now we can send the reply and close the connection because we are done # In[22]: connection.sendall(b"""HTTP/1.1 200 OK Content-type: text/html

hello, world

""") connection.close() # Wrapping this all in a single function that handles a complete request # In[13]: 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

hello, world

""") connection.close() # In[15]: handle_request(listen_socket) # In[ ]: