~ubuntu-branches/ubuntu/vivid/pyzmq/vivid

« back to all changes in this revision

Viewing changes to examples/pubsub/topics_sub.py

  • Committer: Bazaar Package Importer
  • Author(s): Miguel Landaeta
  • Date: 2010-09-08 13:50:41 UTC
  • Revision ID: james.westby@ubuntu.com-20100908135041-bogeb6ykukjrcd89
Tags: upstream-0.1.20100703+git18f5d06155
ImportĀ upstreamĀ versionĀ 0.1.20100703+git18f5d06155

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python
 
2
"""Simple example of publish/subscribe illustrating topics.
 
3
 
 
4
Publisher and subscriber can be started in any order, though if publisher
 
5
starts first, any messages sent before subscriber starts are lost.  More than
 
6
one subscriber can listen, and they can listen to  different topics.
 
7
 
 
8
Topic filtering is done simply on the start of the string, e.g. listening to
 
9
's' will catch 'sports...' and 'stocks'  while listening to 'w' is enough to
 
10
catch 'weather'.
 
11
"""
 
12
 
 
13
#
 
14
#    Copyright (c) 2010 Brian E. Granger, Fernando Perez
 
15
#
 
16
#    This file is part of pyzmq.
 
17
#
 
18
#    pyzmq is free software; you can redistribute it and/or modify it under
 
19
#    the terms of the Lesser GNU General Public License as published by
 
20
#    the Free Software Foundation; either version 3 of the License, or
 
21
#    (at your option) any later version.
 
22
#
 
23
#    pyzmq is distributed in the hope that it will be useful,
 
24
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
 
25
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
26
#    Lesser GNU General Public License for more details.
 
27
#
 
28
#    You should have received a copy of the Lesser GNU General Public License
 
29
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
30
 
 
31
import sys
 
32
import time
 
33
 
 
34
import zmq
 
35
import numpy
 
36
 
 
37
def main():
 
38
    if len (sys.argv) < 2:
 
39
        print 'usage: subscriber <connect_to> [topic topic ...]'
 
40
        sys.exit (1)
 
41
 
 
42
    connect_to = sys.argv[1]
 
43
    topics = sys.argv[2:]
 
44
 
 
45
    ctx = zmq.Context()
 
46
    s = ctx.socket(zmq.SUB)
 
47
    s.connect(connect_to)
 
48
 
 
49
    # manage subscriptions
 
50
    if not topics:
 
51
        print "Receiving messages on ALL topics..."
 
52
        s.setsockopt(zmq.SUBSCRIBE,'')
 
53
    else:
 
54
        print "Receiving messages on topics: %s ..." % topics
 
55
        for t in topics:
 
56
            s.setsockopt(zmq.SUBSCRIBE,t)
 
57
    print
 
58
    try:
 
59
        while True:
 
60
            topic, msg = s.recv_multipart()
 
61
            print '   Topic: %s, msg:%s' % (topic, msg)
 
62
    except KeyboardInterrupt:
 
63
        pass
 
64
    print "Done."
 
65
 
 
66
if __name__ == "__main__":
 
67
    main()