Source

green380 / examples / http_server.py

import gthread
import socket

def handler(sock, addr):
    print('Handling connection from', addr)
    header = yield from sock.until_recv_term(b'\r\n\r\n')
    print('Received header:', header)
    yield from sock.until_sendall('Hello {}!\n'.format(addr).encode())
    sock.close()

def serve():
    sock = gthread.socket()
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    sock.bind(('', 8080))
    sock.listen(socket.SOMAXCONN)
    while True:
        new_sock, addr = yield from sock.until_accept()
        gthread.spawn(handler, new_sock, addr)

gthread.spawn(serve)

gthread.run()