Source

green380 / examples / http_server.py

#!/usr/bin/env python3.3

import socket
#
import green380

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()

@green380.spawn
def server():
    sock = green380.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()
        green380.spawn(handler, new_sock, addr)

green380.run()