gpt4 book ai didi

python - ZeroMQ 2 REQ/REP 以允许嵌套对话

转载 作者:行者123 更新时间:2023-12-01 03:02:06 25 4
gpt4 key购买 nike

我希望发生以下情况:

有一个main_socket,任何人都可以与之交谈。

客户端将发送“READ”并等待服务器发出“OK”,然后再执行此操作。

客户端将发送“WRITE”,当他们收到“OK”时,则意味着他们可以执行写入操作。每个人都应该等待这一点。所以我想到了另一个 REQ/REP channel ,它嵌套在主循环中。服务器将开始监听 write_socket 上的消息,当客户端写入后,它将向 write_socket 发送一条消息。

但不幸的是这不起作用,我不知道为什么。

服务器.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")

客户端.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

我怎样才能让这个案例发挥作用?

最佳答案

这只是一种预感,但是:问题可能是,即使还有一个绑定(bind)套接字,例如localhost:5556,也可以成功绑定(bind)0.0.0.0:5556 127.0.0.1:5556

在这种情况下,绑定(bind)到0.0.0.0:5556的套接字将继续接收到127.0.0.1之外的任何其他地址的连接;并包括 IPv6,但对 127.0.0.1:5556 的连接尝试将被其他地方的另一个 TCP 服务器套接字接受

关于python - ZeroMQ 2 REQ/REP 以允许嵌套对话,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43705169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com