Chinaunix首页 | 论坛 | 博客
  • 博客访问: 779803
  • 博文数量: 239
  • 博客积分: 60
  • 博客等级: 民兵
  • 技术积分: 1045
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-22 18:25
文章分类

全部博文(239)

文章存档

2019年(9)

2018年(64)

2017年(2)

2016年(26)

2015年(30)

2014年(41)

2013年(65)

2012年(2)

分类: 架构设计与优化

2018-08-08 20:46:27

参考:
实现request_reply_processes.py

点击(此处)折叠或打开

  1. import zmq
  2. import time
  3. import sys
  4. from multiprocessing import Process

  5. def server(port="5556"):
  6.     context = zmq.Context()
  7.     socket = context.socket(zmq.REP)
  8.     socket.bind("tcp://*:%s" % port)
  9.     print ("Running server on port: ", port)
  10.     # serves only 5 request and dies
  11.     for reqnum in range(5):
  12.         # Wait for next request from client
  13.         message = socket.recv()
  14.         print ("Received request #%s: %s" % (reqnum, message))
  15.         socket.send( ("World from %s" % port).encode("ascii") )
  16.          
  17. def client(ports=["5556"]):
  18.     context = zmq.Context()
  19.     print ("Connecting to server with ports %s" % ports)
  20.     socket = context.socket(zmq.REQ)
  21.     for port in ports:
  22.         socket.connect ("tcp://localhost:%s" % port)
  23.     for request in range (20):
  24.         print ("Sending request ", request,"...")
  25.         socket.send ("Hello".encode("ascii"))
  26.         message = socket.recv()
  27.         print ("Received reply ", request, "[", message, "]")
  28.         time.sleep (1)


  29. if __name__ == "__main__":
  30.     # Now we can run a few servers
  31.     server_ports = range(5550,5558,2)
  32.     for server_port in server_ports:
  33.         Process(target=server, args=(server_port,)).start()
  34.         
  35.     # Now we can connect a client to all these servers
  36.     Process(target=client, args=(server_ports,)).start()


运行:
#python3 request_reply_processes.py
阅读(1433) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~