Alexander
Alexander

Reputation: 5861

Tornado WebSocket Question

Finally decided to go with Tornado as a WebSocket server, but I have a question about how it's implemented.

After following a basic tutorial on creating a working server, I ended up with this:

#!/usr/bin/env python

from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.web import Application
from tornado.websocket import WebSocketHandler

class Handler(WebSocketHandler):
        def open(self):
            print "New connection opened."

        def on_message(self, message):
                print message


        def on_close(self):
                print "Connection closed."

print "Server started."
HTTPServer(Application([("/", Handler)])).listen(1024)
IOLoop.instance().start()

It works great and all, but I was wondering if the other modules (tornado.httpserver, tornado.ioloop, and tornado.web) are actually needed to run the server.

It's not a huge issue having them, but I just wanted to make sure there wasn't a better way to do whatever they do (I haven't covered those modules at all, yet.).

Upvotes: 1

Views: 3488

Answers (2)

pritam
pritam

Reputation: 2558

  • tornado.httpserver :

    1. A non-blocking, single-threaded HTTP server.
    2. Typical applications have little direct interaction with the HTTPServer class.
    3. HTTPServer is a very basic connection handler. Beyond parsing the HTTP request body and headers, the only HTTP semantics implemented in HTTPServer is HTTP/1.1 keep-alive connections.
  • tornado.ioloop :

    1. An I/O event loop for non-blocking sockets.
    2. So, the ioloop can be used for setting the time-out of the response.
    3. In general, methods on RequestHandler and elsewhere in tornado are not thread-safe. In particular, methods such as write(), finish(), and flush() must only be called from the main thread. If you use multiple threads it is important to use IOLoop.add_callback to transfer control back to the main thread before finishing the request.
  • tornado.web :

    1. Provides RequestHandler and Application classes
    2. Helps with additional tools and optimizations to take advantage of the Tornado non-blocking web server and tools.
    3. So, these are the provisions by this module :
      • Entry points : Hook for subclass initialization.
      • Input
      • Output
      • Cookies

I hope, this will cover the modules you left.

Upvotes: 6

Jeff LaFay
Jeff LaFay

Reputation: 13350

Yes they're needed because you're using each import from each module/package you reference. If you reference something at the top of your source but never use it again in any of the following code then of course you don't need them but in this case you use your imports.

Upvotes: 1

Related Questions