2012-02-01 166 views
12

我想編寫Python代碼來發送文件從客戶端到服務器。服務器需要保存從客戶端發送的文件。但是我的代碼有一些我無法修復的bug。下面是我的服務器代碼:使用XMLRPC從客戶端發送文件到服務器?

# server.py 
from SimpleXMLRPCServer import SimpleXMLRPCServer 
import os 

server = SimpleXMLRPCServer(('localhost', 9000)) 

def save_data(data): 
    handle = open("x123.dat", "wb") 
    handle.write(data) 
    handle.close() 

server.register_function(save_data, 'save_data') 
server.serve_forever() 

而且客戶端代碼:

# client.py 
import sys, xmlrpclib 

proxy = xmlrpclib.Server('http://localhost:9000') 
handle = open(sys.argv[1], "rb") 
proxy.save_data(handle.read()) 
handle.close() 

但後來我跑我的代碼,客戶端返回以下錯誤(這是在Windows上):

Traceback (most recent call last): 
File "client.py", line 6, in <module> proxy.save_data(handle.read()) 
File "c:\python27\lib\xmlrpclib.py", line 1224, in __call__ 
    return self.__send(self.__name, args) 
File "c:\python27\lib\xmlrpclib.py", line 1575, in __request 
    verbose=self.__verbose 
File "c:\python27\lib\xmlrpclib.py", line 1264, in request 
    return self.single_request(host, handler, request_body, verbose) 
File "c:\python27\lib\xmlrpclib.py", line 1297, in single_request 
    return self.parse_response(response) 
File "c:\python27\lib\xmlrpclib.py", line 1473, in parse_response 
    return u.close() 
File "c:\python27\lib\xmlrpclib.py", line 793, in close 
    raise Fault(**self._stack[0]) 
xmlrpclib.Fault: <Fault 1: "<class 'xml.parsers.expat.ExpatError'>:not well-formed (invalid token): line 7, column 1"> 

我有一些問題:

  1. 如何解決上述錯誤?

  2. 我的代碼有時需要傳輸一些大文件。由於我的方法非常簡單,所以我懷疑移動大數據是否有效。任何人都可以請建議一個更好的方法來移動大文件? (當然最好在Python上使用XMLRPC)

回答

12

服務器端:

def server_receive_file(self,arg): 
     with open("path/to/save/filename", "wb") as handle: 
      handle.write(arg.data) 
      return True 

客戶端:

with open("path/to/filename", "rb") as handle: 
    binary_data = xmlrpclib.Binary(handle.read()) 
client.server_receive_file(binary_data) 

這爲我工作。

2

你想看看xmlrpclib Binary object。通過這個類,你可以對base64字符串進行編碼和解碼。

相關問題