Changed around the sockets in the bridge for claritly, tidied up the main code and added some module docs

This commit is contained in:
Ben Ford
2010-09-30 06:04:26 +01:00
parent 7ed9aec6a1
commit 1825a7b260
2 changed files with 23 additions and 17 deletions

View File

@@ -4,13 +4,13 @@ from zmq.devices import Device
if __name__ == "__main__":
usage = 'usage: chat_bridge pub_address sub_address'
usage = 'usage: chat_bridge sub_address pub_address'
if len (sys.argv) != 3:
print usage
sys.exit(1)
pub_addr = sys.argv[1]
sub_addr = sys.argv[2]
sub_addr = sys.argv[1]
pub_addr = sys.argv[2]
print "Recieving on %s" % sub_addr
print "Sending on %s" % pub_addr
device = Device(FORWARDER, SUB, PUB)

View File

@@ -1,5 +1,19 @@
import os, sys
"""This is a websocket chat example with many servers. A client can connect to
any of the servers and their messages will be received by all clients connected
to any of the servers.
Run the examples like this:
$ python examples/chat_bridge.py tcp://127.0.0.1:12345 tcp://127.0.0.1:12346
and the servers like this (changing the port for each one obviously):
$ python examples/distributed_websocket_chat.py -p tcp://127.0.0.1:12345 -s tcp://127.0.0.1:12346 7000
So all messages are published to port 12345 and the device forwards all the
messages to 12346 where they are subscribed to
"""
import os, sys
import eventlet
from collections import defaultdict
from eventlet import spawn_n, sleep
@@ -30,7 +44,8 @@ class IDName(object):
def unpack_message(self, msg):
sender, message = msg
sender_name = 'you said' if sender.id == self.id else '%s says' % sender
sender_name = 'you said' if sender.id == self.id \
else '%s says' % sender
return "%s: %s" % (sender_name, message)
@@ -39,11 +54,7 @@ participants = defaultdict(IDName)
def subscribe_and_distribute(sub_socket):
global participants
while True:
try:
msg = sub_socket.recv_pyobj()
except:
print 'exception in recv'
msg = sub_socket.recv_pyobj()
for ws, name_id in participants.items():
to_send = name_id.unpack_message(msg)
if to_send:
@@ -69,8 +80,6 @@ def handle(ws):
m = 'Changed name from %s' % old_name
pub_socket.send_pyobj(name_id.pack_message(m))
sleep()
except:
raise
finally:
del participants[ws]
@@ -105,16 +114,13 @@ if __name__ == "__main__":
pub_socket = ctx.socket(zmq.PUB)
pub_socket.connect(pub_addr)
print "Publishing to %s" % pub_addr
except:
raise
try:
sub_socket = ctx.socket(zmq.SUB)
sub_socket.connect(sub_addr)
sub_socket.setsockopt(zmq.SUBSCRIBE, "")
print "Subscribing to %s" % sub_addr
except:
raise
print "Couldn't create sockets\n", usage
sys.exit(1)
spawn_n(subscribe_and_distribute, sub_socket)
listener = eventlet.listen(('127.0.0.1', port))