在我的项目下,我需要重复构造和销毁上下文,但这会导致错误。
例如:
import zmq
for i in range(100):
print(i)
context = zmq.Context()
data_socket = context.socket(zmq.SUB)
data_socket.connect("tcp://127.0.0.1:5552")
data_socket.setsockopt_string(zmq.SUBSCRIBE, "")
context.destroy()
它返回
0
1
2
3
4
5
6
7
8
9
10
11
12
13
Traceback (most recent call last):
File "test.py", line 7, in <module>
data_socket.connect("tcp://127.0.0.1:5552")
File "zmq/backend/cython/socket.pyx", line 580, in zmq.backend.cython.socket.Socket.connect
File "zmq/backend/cython/checkrc.pxd", line 25, in zmq.backend.cython.checkrc._check_rc
zmq.error.ZMQError: Socket operation on non-socket
答案 0 :(得分:1)
套接字选项必须放在.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)
出局:
('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)
.
.
.