我正在使用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)
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)
我无法将用户输入从服务器发送到客户端,因为当我按Enter键时无法发送,但能够从服务器向客户端发送和接收硬编码消息。当我这样做时,有时会在客户端收到从服务器端收到的消息。我不确定这是否是由于两个脚本都在localhost上运行而且套接字内部存在冲突。
例如,
data = "random data"
输出:
Received: random data
Counter: 4
Received: Client has received message from server: random data
Received: random data
Counter: 5
Received: random data
Counter: 6
如何发送用户输入并防止客户端在localhost上接收从客户端到服务器收到的消息(如果这是问题)?
答案 0 :(得分:0)
我修复了 input()
问题。我意识到Sublime3无法运行输入命令。我通过安装SublimeREPL包修复了这个问题。
虽然我仍然没有具体的想法,为什么客户端会在localhost上收到有时从客户端收到消息的消息。