Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

example programs

  • Loading branch information...
commit 89f2df13d003c63d32f8ca669a565e5cefb69a81 1 parent bb88f27
@wil authored
Showing with 78 additions and 0 deletions.
  1. +43 −0 src/thelloworld.py
  2. +35 −0 src/tsockhttp.py
View
43 src/thelloworld.py
@@ -0,0 +1,43 @@
+#!/usr/bin/env python
+#
+# Copyright 2009 Facebook
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+
+import tornado.httpserver
+import tornado.ioloop
+import tornado.options
+import tornado.web
+
+from tornado.options import define, options
+
+define("port", default=8888, help="run on the given port", type=int)
+
+
+class MainHandler(tornado.web.RequestHandler):
+ def get(self):
+ self.write("Hello, world")
+
+
+def main():
+ tornado.options.parse_command_line()
+ application = tornado.web.Application([
+ (r"/", MainHandler),
+ ])
+ http_server = tornado.httpserver.HTTPServer(application)
+ http_server.listen(options.port)
+ tornado.ioloop.IOLoop.instance().start()
+
+
+if __name__ == "__main__":
+ main()
View
35 src/tsockhttp.py
@@ -0,0 +1,35 @@
+# taken from http://nichol.as/asynchronous-servers-in-python
+
+import errno
+import functools
+import socket
+from tornado import ioloop, iostream
+
+
+def connection_ready(sock, fd, events):
+ while True:
+ try:
+ connection, address = sock.accept()
+ except socket.error, e:
+ if e[0] not in (errno.EWOULDBLOCK, errno.EAGAIN):
+ raise
+ return
+ connection.setblocking(0)
+ stream = iostream.IOStream(connection)
+ stream.write("HTTP/1.0 200 OK\r\nContent-Length: 5\r\n\r\nPong!\r\n", stream.close)
+
+if __name__ == '__main__':
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ sock.setblocking(0)
+ sock.bind(("", 8010))
+ sock.listen(5000)
+
+ io_loop = ioloop.IOLoop.instance()
+ callback = functools.partial(connection_ready, sock)
+ io_loop.add_handler(sock.fileno(), callback, io_loop.READ)
+ try:
+ io_loop.start()
+ except KeyboardInterrupt:
+ io_loop.stop()
+ print "exited cleanly"

0 comments on commit 89f2df1

Please sign in to comment.
Something went wrong with that request. Please try again.