首先是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