在Python ZMQ发布者/订阅者样本模板中,发布者使用.bind()方法,订阅者使用连接到绑定IP地址的.connect()方法.
但是我们可以用另一个替换.bind()和.connect().
我的问题是,下面确定的两个案例有什么区别?
(在这些情况下两个脚本工作正常)
第一种情况,默认情况下:
pub1.py:
import zmq
import time
from datetime import datetime
def create_pub_socket():
context = zmq.Context()
socket = context.socket(zmq.PUB)
socket.bind("tcp://127.0.0.1:9002") # notice
return socket
def publish(pub_socket):
message = {
'data': 'hi my name is benyamin','time': datetime.now().strftime('%Y-%m-%dT%H:%M:%S')
}
pub_socket.send_json(message,0)
return message
if __name__ == '__main__':
socket = create_pub_socket()
while True:
print('\n')
print('publisher: ',publish(socket))
time.sleep(1)
sub1.py:
import zmq
if __name__ == '__main__':
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.setsockopt(zmq.SUBSCRIBE,"")
socket.connect("tcp://127.0.0.1:9002") # notice
while True:
data = socket.recv_json()
print('subscriber: ',data)
print('\n')
第二种情况,作为修改后的设置,颠倒了.connect()和.bind()方法的使用:
pub2.py:
import zmq
import time
from datetime import datetime
def create_pub_socket():
context = zmq.Context()
socket = context.socket(zmq.PUB)
socket.connect("tcp://127.0.0.1:9002") # notice
return socket
def publish(pub_socket):
message = {
'data': 'hi my name is benyamin',publish(socket))
time.sleep(1)
sub2.py:
import zmq
if __name__ == '__main__':
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.setsockopt(zmq.SUBSCRIBE,"")
socket.bind("tcp://127.0.0.1:9002") # notice
while True:
data = socket.recv_json()
print('second subscriber: ',data)
print('\n')