Параметры сокета должны быть помещены перед методом .connect()
или .bind()
, и вы можете создать экземпляр объекта из zmq.Context()
.
Попробуйте:
import zmq
context = zmq.Context.instance()
for i in range(100):
print(i)
data_socket = context.socket(zmq.SUB)
data_socket.setsockopt(zmq.SUBSCRIBE, b"")
data_socket.connect("tcp://127.0.0.1:5552")
context.destroy()
[ Ваш ответ ]:
Однако, если вы хотите действовать по своему усмотрению, вы должны закрывать сокет в каждой итерации, чтобы ваш фрагмент кода был:
import zmq
for i in range(100):
ctx = zmq.Context.instance()
sock = ctx.socket(zmq.SUB)
sock.setsockopt(zmq.SUBSCRIBE, b'')
sock.connect('tcp://127.0.0.1:5552')
sock.close() # Note
ctx.destroy()
print('ctx closed status: ', ctx.closed, ' iteration: ', i)
Out:
('ctx closed status: ', True, ' iteration: ', 0)
('ctx closed status: ', True, ' iteration: ', 1)
('ctx closed status: ', True, ' iteration: ', 2)
('ctx closed status: ', True, ' iteration: ', 3)
('ctx closed status: ', True, ' iteration: ', 4)
('ctx closed status: ', True, ' iteration: ', 5)
('ctx closed status: ', True, ' iteration: ', 6)
('ctx closed status: ', True, ' iteration: ', 7)
('ctx closed status: ', True, ' iteration: ', 8)
('ctx closed status: ', True, ' iteration: ', 9)
('ctx closed status: ', True, ' iteration: ', 10)
('ctx closed status: ', True, ' iteration: ', 11)
('ctx closed status: ', True, ' iteration: ', 12)
('ctx closed status: ', True, ' iteration: ', 13)
('ctx closed status: ', True, ' iteration: ', 14)
.
.
.