python 多线程 多进程 zmq_Python中的简单客户端/服务器ZMQ,每个请求发送多行

这是我在

Python下第一次接触ZMQ,我希望服务器在收到客户端的请求时发送多行.

我添加到ZMQ在服务器端提供的示例中的代码是:

with open("test.txt", 'r') as f:

for line in f:

socket.send_string(line.rstrip("\n"))

问题是如何使服务器发送所有行或如何使客户端不在服务器之前发送请求

完成从test.txt发送所有行

客户

import zmq

context = zmq.Context()

print("Connecting to hello world server")

socket = context.socket(zmq.REQ)

socket.connect("tcp://localhost:5555")

for request in range(10):

print("Sending request %s" % request)

socket.send(b"Hello")

message = socket.recv()

print("Received reply %s [ %s ]" % (request, message))

服务器

import time

import zmq

context = zmq.Context()

socket = context.socket(zmq.REP)

socket.bind("tcp://*:5555")

while True:

# Wait for next request from client

message = socket.recv()

print("Received request: %s" % message)

# Do some 'work'

time.sleep(1)

# Send reply back to client

with open("test.txt", 'r') as f:

for line in f:

socket.send_string(line.rstrip("\n"))

客户端日志

Connecting to hello wolrd server

Sending request 0

Received reply 0 [ This is test line 1 ]

Sending request 1

这是它停止的地方,因为服务器生成了下面显示的错误:

服务器日志

line 324, in send_string

return self.send(u.encode(encoding), flags=flags, copy=copy)

File "socket.pyx", line 571, in zmq.backend.cython.socket.Socket.send (zmq/backend/cython/socket.c:5319)

File "socket.pyx", line 618, in zmq.backend.cython.socket.Socket.send (zmq/backend/cython/socket.c:5086)

File "socket.pyx", line 181, in zmq.backend.cython.socket._send_copy (zmq/backend/cython/socket.c:2081)

File "checkrc.pxd", line 21, in zmq.backend.cython.checkrc._check_rc (zmq/backend/cython/socket.c:6032)

zmq.error.ZMQError: Operation cannot be accomplished in current state

Process finished with exit code 1

的test.txt

This is test line 1

This is test line 2

This is test line 3

This is test line 4

This is test line 5

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值