Communicating Simply Between Interpreters
Problem
在不同机器上运行的Python解释器实例之间使用消息来交换数据
Solution
可以使用multiprocessing.connection模块来解决
以下是一个简单的echo服务器
from multiprocessing.connection import Listener import traceback def echo_client(conn): try: while True: msg=conn.recv() conn.send(msg) except EOFError: print('Connection closed') def echo_server(address,authkey): serv=Listener(address,authkey=authkey) while True: try: client=serv.accept() echo_client(client) except Exception: traceback.print_exc() echo_server(('',25000),authkey=b'peekaboo')
然后执行这个程序
In [1]: from multiprocessing.connection import Client In [2]: c=Client(('localhost',25000),authkey=b'peekaboo') In [3]: c.send('hello') In [4]: c.recv() Out[4]: 'hello' In [5]: c.send(42) In [6]: c.recv() Out[6]: 42 In [7]: c.send([1,2,3,4,5]) In [8]: c.recv() Out[8]: [1, 2, 3, 4, 5]
不像低级的socket,通过这样发送的消息保持完整,没有受到损坏。
Implementing Remote Proceduer Calls
Problem
想要在一个消息队列层之上实现简单的远程过程调用RPC
Solution
RPC可以很容易的通过使用picke模块来实现
http://chimera.labs.oreilly.com/books/1230000000393/ch11.html