问题
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 192.168.1.56-192.168.1.65. I've followed this tutorial https://learning-0mq-with-pyzmq.readthedocs.io/en/latest/pyzmq/patterns/pubsub.html, however, it doesn't work. On one machine "server", the data is printed, however, at the subscriber "client", it doesn't receive anything.
Have you tried this or do you know which could be the cause?
回答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.
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" if len( sys.argv ) < 2 else int( sys.argv[1] ) )
socket.setsockopt( zmq.LINGER, 0 )
while True:
topic = random.randrange( 9999, 10005 )
messagedata = random.randrange( 1, 215) - 80
print "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" if len( sys.argv ) < 2 else int( sys.argv[1] ) )
if len( sys.argv ) > 2:
socket.connect( "tcp://localhost:%s" % int( sys.argv[2] ) )
socket.setsockopt( zmq.LINGER, 0 )
# Subscribe to zipcode, default is NYC, 10001
pass; topicfilter = "10001"
socket.setsockopt( zmq.SUBSCRIBE, topicfilter )
# Process 5 updates
total_value = 0
for update_nbr in range (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 distributed-computing 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.
来源:https://stackoverflow.com/questions/64893702/how-pub-sub-with-pyzmq-between-two-vms