Python 聊天室 II(SimpleXMLRPCServer模塊實現)

並非上一個用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)
相關文章
相關標籤/搜索