Skip to content Skip to sidebar Skip to footer

How Pub/sub With Pyzmq Between Two Vms

I have two VMs (VirtualBOx, Ubuntu 18.04 and python-zmq) running within the same physical machine (Win10). Both machines are configured as Bridge and they can be ping successfully

Solution 1:

Q : "Have you tried this or do you know which could be the cause?"

Yes, a copy-paste source code ( used the same Scenario #2, as you did, having a solo SUB ) works fine, yet rather use the modified code template below.

enter image description here


A PUB-archetype Publisher :

Using ZeroMQ v.2.11, py-2.7:

import zmq
import random
import sys
import time

context = zmq.Context()
try:
    socket  = context.socket( zmq.PUB )
    socket.bind( "tcp://*:%s" % "5556"iflen( sys.argv ) < 2elseint( sys.argv[1] ) )
    socket.setsockopt( zmq.LINGER, 0 )

    whileTrue:
       topic       = random.randrange( 9999, 10005 )
       messagedata = random.randrange( 1, 215) - 80print"Topis = {0: >6d}: DATA = {1: >4d}".format( topic, messagedata )
       socket.send( "%d %d" % ( topic, messagedata ) )
       time.sleep( 1 )

except:
    print"EXC'd here"finally:
    "WILL gracefully CLOSE Socket()-instance(s) and TERM Context()-instance(s)"
    socket.close()
    context.term()

A SUB-archetype Listener :

import sys
import zmq

context = zmq.Context()

try:
    socket = context.socket( zmq.SUB )
    
    print"WILL start connecting: for further collecting updates from weather server..."
    socket.connect( "tcp://localhost:%s" % "5556"iflen( sys.argv ) < 2elseint( sys.argv[1] ) )

    iflen( sys.argv ) > 2:
         socket.connect( "tcp://localhost:%s" % int( sys.argv[2] ) )

    socket.setsockopt( zmq.LINGER, 0 ) 

    # Subscribe to zipcode, default is NYC, 10001pass;                             topicfilter = "10001"
    socket.setsockopt( zmq.SUBSCRIBE, topicfilter )
    
    # Process 5 updates
    total_value = 0for update_nbr inrange (5):
        string = socket.recv()
        topic, messagedata = string.split()
        total_value += int( messagedata )
        print topic, messagedata

    print"UPDATE: Average messagedata value for topic '%s' was %dF" % ( topicfilter, total_value / update_nbr )
      
except:
    print"EXC'd here"finally:
    print"WILL gracefully CLOSE Socket()-instance(s) and TERM Context()-instance(s)"
    socket.close()
    context.term()

Your experiment fails after modifying the SUB-side code on defining an invalid TCP/IP-target where the code cannot, for obvious reasons, successfully .connect(). Go get a read about the solution here.

Post a Comment for "How Pub/sub With Pyzmq Between Two Vms"