Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A ZeroMQ - SocketIO gateway using TornadIO
import os
import zmq
from zmq.eventloop import ioloop, zmqstream
ioloop.install()
import tornado
import tornado.web
import tornadio
import tornadio.router
import tornadio.server
ROOT = os.path.normpath(os.path.dirname(__file__))
class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.render("index.html")
class ClientConnection(tornadio.SocketConnection):
clients = set()
@classmethod
def dispatch_message(cls, message):
for client in cls.clients:
client.send(message)
def on_open(self, *args, **kwargs):
self.clients.add(self)
def on_message(self, message):
pass
def on_close(self):
self.clients.remove(self)
WebClientRouter = tornadio.get_router(ClientConnection)
application = tornado.web.Application(
[(r"/", IndexHandler), WebClientRouter.route()],
enabled_protocols = ['websocket', 'flashsocket', 'xhr-multipart', 'xhr-polling'],
flash_policy_port = 843,
flash_policy_file = os.path.join(ROOT, 'flashpolicy.xml'),
socket_io_port = 8001
)
if __name__ == '__main__':
import logging
logging.getLogger().setLevel(logging.DEBUG)
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.bind('tcp://127.0.0.1:5000')
socket.setsockopt(zmq.SUBSCRIBE, '')
stream = zmqstream.ZMQStream(socket, tornado.ioloop.IOLoop.instance())
stream.on_recv(ClientConnection.dispatch_message)
tornadio.server.SocketServer(application)
<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-access-from domain="*" to-ports="*" />
</cross-domain-policy>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="http://cdn.socket.io/stable/socket.io.js"></script>
<script>WEB_SOCKET_SWF_LOCATION = 'http://cdn.socket.io/stable/WebSocketMain.swf';</script>
<script>
window.onload = function() {
var s = new io.Socket(window.location.hostname, {port: 8001, rememberTransport: false});
s.connect();
s.addEvent('connect', function() {
$("#chat").append("<div>Connected!</div>");
});
s.addEvent('message', function(data) {
$("#chat").append("<div>" + data + "</div>");
});
};
</script>
</head>
<body>
<h3>0MQ - WebSocket test</h3>
<div id="chat" style="width: 60em; height: 20em; overflow:auto; border: 1px solid black">
</div>
</body>
</html>
import zmq
context = zmq.Context()
socket = context.socket(zmq.PUB)
socket.setsockopt(zmq.LINGER, 0) # discard unsent messages on close
socket.connect('tcp://127.0.0.1:5000')
while True:
msg = raw_input('> ')
if msg == 'quit':
break
else:
socket.send(msg)
socket.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment