啰嗦几句:
这个经典的模式在zeroMQ中是请求-应答状态的,不能同时send多个数据,只能ababab这样。还有这里send_pyobj是pyzmq特有的,用以传递python的对象,如同socket的send。看了点zeromq的书,书本里面都是进行一些简单的文字交流,想着自己上手写一个文本文件收发程序,记录下来权当做笔记,如有不当之处,还请各位指出~。具体的思路如下所示:
具体代码:
客户端代码:
# @Time : 2018/12/9 22:00
# @Author : Ctry
# @Email : c_mktry@@163.com
# @File : server_txt.py
# @Software: PyCharm
import zmq
import os
#初始化一些参数
FILENAME = 'test.txt'
context = zmq.Context()
socket = context.socket(zmq.REQ)
socket.connect("tcp://localhost:4560")
def send_data():
# 确认文件是否可用
if not os.path.isfile(FILENAME):
print('isfile 失败')
# 打开文件准备读
print('open the file for read ')
with open(FILENAME, 'r') as fn: # 依次读取每行
# line = line.strip() # 去掉每行头尾空白
line = fn.readlines(256)
print(line)
print(type(line))
socket.send_pyobj(line)
print('收到服务器的回应', socket.recv_pyobj())
fn.close()
if __name__ == '__main__':
send_data()
服务器端代码:
# @Time : 2018/12/9 22:00
# @Author : Ctry
# @Email : c_mktry@@163.com
# @File : server_txt.py
# @Software: PyCharm
import zmq
import os
PATH = 'received.txt'
# 建立 context 和 socket
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind('tcp://*:4560')
def write_file():
print('path is ',PATH)
print('preparing to write the data (received)')
# preparing to write the data
data = socket.recv_pyobj()
print(data)
# Write the chunk to the file
dest.writelines(data)
data.reverse()
print(data)
socket.send_pyobj(data)
dest.close()
if __name__ == '__main__':
dest = open(os.path.basename('received.txt'), 'w+')
write_file()
test.txt的内容如下:
I love Beijing I love China Beijing is the capital of China
运行结果如下所示: