Created
June 24, 2011 09:41
-
-
Save estin/1044504 to your computer and use it in GitHub Desktop.
Python async http "hello" server (Python 3.x)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import asyncore | |
import socket | |
ANSWER = 'HTTP/1.0 200 OK\r\n' + \ | |
'Content-Type: text/html; charset=utf-8\r\n' + \ | |
'Content-Length: 5\r\n' + \ | |
'Connection: close\r\n\r\n' + \ | |
'hello' | |
class HelloHandler(asyncore.dispatcher): | |
def __init__(self, conn_sock): | |
self.buffer = bytes(ANSWER, 'iso-8859-1') | |
asyncore.dispatcher.__init__(self, conn_sock) | |
def handle_read(self): | |
self.recv(1024) | |
def handle_write(self): | |
if self.buffer: | |
sent = self.send(self.buffer) | |
self.buffer = self.buffer[sent:] | |
else: | |
self.close() | |
class HelloServer(asyncore.dispatcher): | |
def __init__(self, host, port): | |
asyncore.dispatcher.__init__(self) | |
self.create_socket(socket.AF_INET, socket.SOCK_STREAM) | |
self.set_reuse_addr() | |
self.bind((host, port)) | |
self.listen(5) | |
def handle_accept(self): | |
pair = self.accept() | |
if pair is None: | |
pass | |
else: | |
sock, addr = pair | |
# New handler for each requst | |
HelloHandler(sock) | |
if __name__ == '__main__': | |
server = HelloServer('localhost', 8080) | |
asyncore.loop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment