我希望发生以下情况:
有一个main_socket
,任何人都可以与之交谈。
客户端将发送“READ”并等待服务器发出的“OK”。
客户获得“OK”后将发送“WRITE”,这表示他们可以执行写操作。每个人都应该等待。因此,我想到了另一个嵌套在主循环中的REQ/REP channel 。服务器将开始在write_socket
上监听消息,并且在客户端编写后,它将向write_socket
发送消息。
不幸的是,这行不通,我也不知道为什么。
server.py
import time
import zmq
context = zmq.Context()
main_socket = context.socket(zmq.REP)
main_socket.bind("tcp://*:5555")
write_socket = context.socket(zmq.REP)
write_socket.bind("tcp://*:5556")
print("ready to receive")
while True:
# Wait for next request from client
print("server receiving main")
message = main_socket.recv()
print("server received main", message)
if message == b"WRITE":
main_socket.send(b"WRITE")
print("server receiving write")
message = write_socket.recv()
print("server received write", message)
write_socket.send(b"OK")
else:
main_socket.send(b"OK")
client.py
import zmq
import time
context = zmq.Context()
# Socket to talk to server
print("Connecting to main server…")
main_socket = context.socket(zmq.REQ)
main_socket.connect("tcp://localhost:5555")
print("Connecting to write server…")
write_socket = context.socket(zmq.REQ)
write_socket.connect("tcp://localhost:5556")
print("starting")
t1 = time.time()
for i in range(10000):
print("client sending main", b"WRITE")
main_socket.send(b"WRITE")
print("client receiving main")
message = main_socket.recv()
print("client received main", message)
print("client writing")
print("writing...")
print("client written")
time.sleep(5)
print("client sending write", b"WRITE")
write_socket.send(b"WRITE")
print("client receiving write")
message = write_socket.recv()
print("client received write", message)
打印以下内容:
服务器
ready to receive
server receiving main
server received main b'WRITE'
server receiving write
客户
Connecting to read server…
Connecting to write server…
starting
client sending main b'WRITE'
client receiving main
client received main b'WRITE'
client writing
client written
client sending write b'WRITE'
client receiving write
我该如何处理此案?
最佳答案
这只是预感,但问题是:即使0.0.0.0:5556
也有绑定(bind)套接字声明,也就是localhost:5556
,问题仍然可能成功绑定(bind)127.0.0.1:5556
。
在那种情况下,绑定(bind)到0.0.0.0:5556
的套接字将继续接收到除127.0.0.1
之外的任何其他地址的连接; (包括IPv6),但尝试127.0.0.1:5556
的连接将由其他地方的另一个TCP服务器套接字accept
进行连接。
关于python - ZeroMQ 2 REQ/REP允许嵌套对话,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43705169/