Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web sockets / Tornado - Notify client on database update

I'm trying to use a Tornado web socket server to notify my user when changes are made to a database in realtime. I was hoping to use HTML5 web sockets for this, even though most browsers don't support them. None of the demos that come with the Tornado package use web sockets and they are not mentioned in the documentation, so I have no idea how to get started. The few examples I could find on google either don't work or are poorly documented.

Does anyone have any examples of how I can use Tornado to push data to a client when a MySQL database has been updated or something similar I can use to learn from?

like image 599
Hanpan Avatar asked May 25 '11 22:05

Hanpan


2 Answers

I've had success using the socket.io client and tornadio on the server end. Socket.IO provides an abstraction over websockets and provides fallbacks if websockets aren't supported by the browser (long polling, flash socket, etc.).

In order to use it you just need to write a tornadio script a la the tornadio documentation that monitors your database and then include the socket.io JavaScript in your web pages and have it establish a connection to wherever your tornadio server resides at the URL route you specified in your tornadio script.

like image 30
A Lee Avatar answered Nov 17 '22 15:11

A Lee


A Lee's answer is a good one, you probably want socket.io if you need to support older browsers.

Websockets are very easy in tornado though:

import tornado.websocket

  class EchoWebSocket(tornado.websocket.WebSocketHandler):
      def open(self):
          print "WebSocket opened"

      def on_message(self, message):
          self.write_message(u"You said: " + message)

      def on_close(self):
          print "WebSocket closed"

Then route it as any other handler, and include Websocket Javascript in your views:

  var ws = new WebSocket("ws://localhost:8888/websocket");
  ws.onopen = function() {
     ws.send("Hello, world");
  };
  ws.onmessage = function (evt) {
     alert(evt.data);
  };

For more info, see the source: https://github.com/facebook/tornado/blob/master/tornado/websocket.py

like image 107
Cole Maclean Avatar answered Nov 17 '22 14:11

Cole Maclean