PAIR/PAIR 通信原型中的 PyZMQ 用户输入()

PyZMQ user input() in PAIR/PAIR communication archetype

我正在使用 PyZMQ 创建一个简单的 PAIR/PAIR 通信原型消息传递模式。

配对服务器

import zmq
import random
import sys
import time

port = "9999"
context = zmq.Context()
socket = context.socket(zmq.PAIR)
print("Binding socket to port: " + str(port))
socket.bind("tcp://*:%s" % port)
print("Connection has been established")

while True:
    data = input("Enter: ")
    socket.send_string(data)
    msg = str(socket.recv(), "utf-8")
    print("Received: ",msg)
    time.sleep(2)

PairClient

import zmq
import random
import sys
import time

port = "9999"
context = zmq.Context()
socket = context.socket(zmq.PAIR)
print("Connecting socket to port: " + str(port))
socket.connect("tcp://localhost:%s" % port)
print("Connected")

count = 0
response = 1

while True:
    msg = str(socket.recv(), "utf-8")
    print("Received: ",msg)
    count = count + 1
    print("Counter: ",count)

    if count == response:
        data = "Client has received message from server: " + msg
        socket.send_string(data)
        response = response + 1
        time.sleep(2)

我无法将用户输入从服务器发送到客户端,因为当我按回车键时没有任何传输,但我能够从服务器到客户端发送和接收硬编码消息。当我这样做时,从服务器端收到的消息有时会在客户端收到。我不确定这是否是因为两个脚本都在本地主机上 运行 并且套接字内存在冲突。

例如,

配对服务器

data = "random data"

PairClient

输出:

Received:  random data
Counter:  4
Received:  Client has received message from server: random data
Received:  random data
Counter:  5
Received:  random data
Counter:  6

如何发送用户输入并防止从客户端接收到服务器的消息被本地主机上的客户端接收(如果这是问题所在)?

我已经解决了 input() 问题。我意识到 Sublime3 无法 运行 输入命令。我通过安装 SublimeREPL 包修复了这个问题。

尽管我仍然不清楚为什么有时从客户端到服务器的消息会被本地主机上的客户端接收到。