码迷,mamicode.com
首页 > 编程语言 > 详细

Python网络编程

时间:2016-03-13 18:17:11      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:python




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


本文出自 “Linux SA John” 博客,请务必保留此出处http://john88wang.blog.51cto.com/2165294/1750514

Python网络编程

标签:python

原文地址:http://john88wang.blog.51cto.com/2165294/1750514

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!