pyzmq 对套接字卡住了

pyzmq pair sockets stuck

我正在关注 pyzmq 文档中的双向对套接字示例。我创建了两个文件, socket1.py 使用此代码

import zmq
import random
import sys
import time

port = "5556"
context = zmq.Context()
socket = context.socket(zmq.PAIR)
socket.connect("tcp://localhost:{}".format(port))
print("Socket created")

i = 0
while True:
    msg = socket.recv()
    print("socket: msg recved")
    print(msg)
    socket.send_string("hello from 1")
    time.sleep(1)
    print(i)

和 socket2.py 使用此代码:

import zmq
import random
import sys
import time

port = "5556"
context = zmq.Context()
socket = context.socket(zmq.PAIR)
socket.connect("tcp://localhost:{}".format(port))
print("Socket created")

i = 0
while True:
    socket.send_string("hello from 2")
    print("socket2: msg sent")
    msg = socket.recv()
    print(msg)
    time.sleep(1)
    print(i)

我 运行 两个独立终端中的文件,但它分别在终端 1 和终端 2 中打印以下消息:

Socket created
Socket created
socket2: msg sent

我无法理解为什么 socket1 收不到 socket2 发送的消息并卡在 socket.recv()。我真的很感激任何帮助。 TIA.

你很接近。第一个例子,socket1.py 需要绑定到端口。 zeromq 会将其转换为监听客户端连接。

import zmq
import random
import sys
import time

port = "5556"
context = zmq.Context()
socket = context.socket(zmq.PAIR)
socket.bind("tcp://localhost:{}".format(port))
print("Socket created")

i = 0
while True:
    msg = socket.recv()
    print("socket: msg recved")
    print(msg)
    socket.send_string("hello from 1")
    time.sleep(1)
    print(i)