Created
January 17, 2014 03:31
-
-
Save jamiesun/8467943 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python | |
#coding:utf-8 | |
import sys, os, re | |
import logging | |
from tornado import ioloop, iostream, httpserver | |
logging.basicConfig(level=logging.INFO, format='%(levelname)s - - %(asctime)s %(message)s', datefmt='[%d/%b/%Y %H:%M:%S]') | |
class SocketConnection(object): | |
stream_set = set([]) | |
def __init__(self, stream, address, *args): | |
logging.info('receive a new connection from %s', address) | |
self.stream = stream | |
self.address = address | |
self.stream_set.add(self.stream) | |
self.stream.set_close_callback(self.on_close) | |
self.stream.read_until('\n', self.on_read_line) | |
def on_read_line(self, data): | |
logging.info('read a new line from %s', self.address) | |
for stream in self.stream_set: | |
stream.write(data, self.on_write_complete) | |
def on_write_complete(self): | |
logging.info('write a line to %s', self.address) | |
if not self.stream.reading(): | |
self.stream.read_until('\n', self.on_read_line) | |
def on_close(self): | |
logging.info('client quit %s', self.address) | |
self.stream_set.remove(self.stream) | |
def main(): | |
httpserver.HTTPConnection = SocketConnection | |
http_server = httpserver.HTTPServer(None) | |
http_server.listen(8888) | |
logging.info('tonado server started.') | |
ioloop.IOLoop.instance().start() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment