并非上一个用SocketServer的聊天室的延续。用远程调用完成的聊天室。python
正好有Java的RMI聊天室的做业,就先用Python写了一个简单的相似远程调用的东西,逻辑完成以后,在Java上写一遍也是水到渠成的事。app
Python没有RMI,但拥有一个SimpleXMLRPCServer模块。函数
原理和RMI相似,不过省去了定义接口和生成stub的过程,并且不只支持调用远程对象,更支持调用远程函数。oop
下面的代码都只调用了远程函数。这点和RMI必须经过远程对象调用方法不一样。this
提及啦,Python算是个OO语言,但不像Java那样彻底的OO,能够彻底不用OO的方式来编写程序。code
基本上下面的程序就是如此,并且相对简洁,一样的RMI下次贴上来,代码量就多了不少,并且注册,接口等一系列事情,很烦。server
固然这个SimpleXMLRPCServer模块有个问题:敢不敢快一点!!!!!基本上读端有大概1秒的延迟,这个略显坑爹了。。xml
from SimpleXMLRPCServer import SimpleXMLRPCServer # list to store the total message ms=[] # remote function # each write client invoke this function to say something, and the message will be store in the ms list def say(s): ms.append(s) # each read client invoke this function to get the latest message. # args: message_no the total message number which this client has received. def showMessage(message_no): if message_no>=0: mst=ms[message_no:] # always to get the latest message which client haven't received. return mst # create the XMLRPCServer svr=SimpleXMLRPCServer(("", 8080), allow_none=True) # regisrer functions svr.register_function(say) svr.register_function(showMessage) # run server svr.serve_forever()
from xmlrpclib import ServerProxy svr=ServerProxy("http://localhost:8080") #connect to server while True: #loop to get input s=raw_input("Zhu Di:") svr.say(s) #Remote invoking the server's function
from xmlrpclib import ServerProxy # connect to server svr=ServerProxy("http://localhost:8080") # the message number which this client has recveied. message_no=0 # remote invoking the function to show the latest message while True: ms=svr.showMessage(message_no) if len(ms)>0: for i in range(len(ms)): print ms[i] message_no+=len(ms)