zeroMQ的request-reply,publish-subscribe和pipeline模式

首先是request-reply

client.py如下:

import zmq
context = zmq.Context()

HOST = '127.0.0.1'
PORT1 = '4096'

php= "tcp://"+HOST +':'+ PORT1

s = context.socket(zmq.REQ)

s.connect(php)
print('clent send STOP')
s.send(('STOP').encode('utf-8'))

msg = s.recv().decode('utf-8')
print('client receive: ',msg)

server.py

import zmq,time,os
context = zmq.Context()

HOST = '127.0.0.1'
PORT1 = '4096'
PORT2 = '4097'

p1= "tcp://"+HOST +':'+ PORT1
p2= "tcp://"+HOST +':'+ PORT2

s = context.socket(zmq.REP)

s.bind(p1)
s.bind(p2)

while True:
	msg = s.recv()
	msg = msg.decode('utf-8')
	print('server receive: ',msg)
	if not 'STOP' == msg:
		s.send((msg+'*******').encode('utf-8'))
	else:
		msg = msg+'*******'
		print('server send: ',msg)
		s.send((msg).encode('utf-8'))
		#time.sleep(2) # 睡眠秒数
		os.system("pause");
		break
	pass

结果如下:

 

publish-request模型

server.py

import zmq,time,os
context = zmq.Context()

HOST = '127.0.0.1'
PORT1 = '4096'
PORT2 = '4097'

p= "tcp://"+HOST +':'+ PORT1

s = context.socket(zmq.PUB)

s.bind(p)

while True:
	time.sleep(2)
	msg = 'time'+time.asctime()
	print('server send: ')
	s.send(msg.encode('utf-8'))

client.py

import zmq,time,os
context = zmq.Context()

HOST = '127.0.0.1'
PORT1 = '4096'

p1= "tcp://"+HOST +':'+ PORT1

s = context.socket(zmq.SUB)

s.connect(p1)
s.setsockopt(zmq.SUBSCRIBE,'time'.encode('utf-8'))

for i in range(5):
	time = s.recv()
	print(time)

使得python界面等待任意键再关闭的代码

import os
os.system("pause");

pipeline代码

source.py

import zmq,time,os,pickle,sys,random
context = zmq.Context()

me = str(sys.argv[1])
s  = context.socket(zmq.PUSH)
SRC1 = '127.0.0.1'
SRC2 = '127.0.0.1'
PORT1 = '4096'
PORT2 = '4096'
src = SRC1 if me == '1' else SRC2
prt = PORT1 if me == '1' else PORT2
p = "tcp://" + src + ":" + prt
s.bind(p)
for i in range(100):
	workload = random.randint(1,100)
	s.send(pickle.dumps((me,workload)))

运行时候:

python source.py 1

worker.py

import zmq,time,os,pickle,sys,random
context = zmq.Context()

me = str(sys.argv[1])
r  = context.socket(zmq.PULL)
SRC1 = '127.0.0.1'
SRC2 = '127.0.0.1'
PORT1 = '4096'
PORT2 = '4096'

p1 = "tcp://" +SRC1 + ":" + PORT1
p2 = "tcp://" +SRC2 + ":" + PORT2

r.connect(p1)
r.connect(p2)
count = 0
while True:
	work = pickle.loads(r.recv())
	count +=1
	print(work[1],count)
	time.sleep(work[1]*0.01)
	if count ==100:
		break

运行时候指令为:

python worker.py 1

结果:source那边很快就结束了,但是子啊worker这边需要一定的时间才可以完整地显示出来,100表示序号,就是接收到的第一百个数字为65

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值