Created
September 12, 2012 17:51
-
-
Save mrjoes/3708549 to your computer and use it in GitHub Desktop.
sockjs-tornado with tornado.gen interface.
This file contains 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 -*- | |
from tornado import ioloop, web, gen, httpclient | |
from sockjs.tornado import SockJSConnection, SockJSRouter | |
class IndexHandler(web.RequestHandler): | |
"""Regular HTTP handler to serve the ping page""" | |
def get(self): | |
self.render('index.html') | |
# Out broadcast connection | |
class GrabConnection(SockJSConnection): | |
def on_message(self, msg): | |
print '1 - Making request' | |
self.handle_request(msg) | |
print '2 - Returned from on_message' | |
@gen.engine | |
def handle_request(self, url): | |
client = httpclient.AsyncHTTPClient() | |
response = yield gen.Task(client.fetch, url) | |
self.send(repr(response.headers)) | |
print '3 - Sent data to client' | |
GrabRouter = SockJSRouter(GrabConnection, '/grab') | |
if __name__ == "__main__": | |
import logging | |
logging.getLogger().setLevel(logging.DEBUG) | |
# Create application | |
app = web.Application( | |
[(r"/", IndexHandler)] + | |
GrabRouter.urls | |
) | |
app.listen(8080) | |
print 'Listening on 0.0.0.0:8080' | |
ioloop.IOLoop.instance().start() |
This file contains 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> | |
<script src="http://cdn.sockjs.org/sockjs-0.3.min.js"></script> | |
<script> | |
$(function() { | |
var conn = new SockJS('http://localhost:8080/grab'); | |
conn.onmessage = function(e) { | |
$('<div/>').text(e.data).appendTo($('#msg')); | |
$('#msg').append('<hr/>'); | |
} | |
$('#grab').click(function() { | |
conn.send('http://www.google.com/'); | |
return false; | |
}); | |
}); | |
</script> | |
</head> | |
<body> | |
<h3>Grab it!</h3> | |
<div id="msg"></div> | |
</body> | |
<a id="grab" href="#">Grab!</a> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment