Python 多线程 XML RPC的实现

python 中的SimpleXMLRPCServer只能支持单线程访问对象.如果想使用多线程的 SimpleXMLRPCServer.最好的办法就是继承ThreadMixIn.简单吧:)下面是代码

服务器端代码 #  -*- Python -*-
#
# server.py -
#
#  Copyright (C) 2007 Leo Chen (hide1713@gmail.com)
#
# $Locker:  $
# $Log: header.el,v $Revision 1.1  2001/02/01 20:15:57  lasse
# Author          : Leo Chen
# Created On      : Sat Jun 16 10:10:28 2007
# Last Modified By: Leo Chen
# Last Modified On: Sat Jun 16 10:10:38 2007
# Update Count    : 1
#
# HISTORY
#
#-*- coding: cp936 -*-
import  SimpleXMLRPCServer,SocketServer
import time,thread

#The server object
class Server:
    count=0
    def __init__(self):
        pass
   
    def ServeMe(self):
        mutex.acquire() #用mutex锁住数据
        Server.count+=1 #更改静态数据
        t=time.strftime("Serve at %I:%M:%S Id is ")+str(Server.count)
        print "Serve Id "+str(Server.count)
        mutex.release()#释放锁
        time.sleep(10)
       
        return t
#多线程实现
class RPCThreading(SocketServer.ThreadingMixIn, SimpleXMLRPCServer.SimpleXMLRPCServer):
    pass
global mutex
mutex =thread.allocate_lock()
server_object = Server()
server = RPCThreading(("localhost", 8888))
server.register_instance(server_object)
 
#Go into the main listener loop
print "Listening"

server.serve_forever()
 
客户端代码
#  -*- Python -*-
#
# client.py -
#
#  Copyright (C) 2007 Leo Chen (hide1713@gmail.com)
#
# $Locker:  $
# $Log: header.el,v $Revision 1.1  2001/02/01 20:15:57  lasse
# Author          : Leo Chen
# Created On      : Sat Jun 16 10:10:56 2007
# Last Modified By: Leo Chen
# Last Modified On: Sat Jun 16 10:10:57 2007
# Update Count    : 1
#
# HISTORY
#
import xmlrpclib
 
server = xmlrpclib.ServerProxy("http://localhost:8888")
 
id = server.ServeMe()
print id

注意.如果有共享数据.操作时要加锁.
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/hide1713/archive/2007/06/16/1654175.aspx

Share and Enjoy:
  • Print this article!
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Live
  • MySpace
  • RSS
  • Slashdot
  • Technorati
  • TwitThis

Related posts:

  1. XML-RPC in Python简介
  2. Python 3.1.1 RC发布
  3. Python 字符串方法详解
  4. python国际化(i18n)和中英文切换
  5. python range()函数的用法
  6. Python Programming – Sqlite for data persistence
  7. Python Daemon(守护进程)
  8. Core Python Programming(1) - Basic
  9. Python list的排序
  10. Python CGI实现用户会话

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Contact us

Admin: Bryan Wu