In Python ZMQ publisher/subscriber sample template, the publisher uses .bind()
method and the subscriber uses .connect()
method, that connected to the bind IP address.
But we can replace .bind()
and .connect()
each with the other.
My question is that what is the difference between two cases that determined below?
(two scripts in these cases work fine)
The first case, as default:
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')
And the second case, as the modified setup, that reversed the use of the .connect()
and .bind()
methods:
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',
'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)
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')