pyzmq对插口卡住

问题描述 投票:0回答:1

我正在遵循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。

python sockets zeromq pyzmq
1个回答
0
投票

您很近。第一个示例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)
© www.soinside.com 2019 - 2024. All rights reserved.