2011-04-14 158 views
3

我用xmlrpc服務器運行簡單的例子,然後按下鍵盤上的Ctrl-C :)。按下鍵盤後xmlrpc服務器的問題

 
from SimpleXMLRPCServer import SimpleXMLRPCServer 
from time import sleep 
import threading,time 

class Test(threading.Thread): 
    def __init__(self): 
     threading.Thread.__init__(self) 
     self.test1 = 0 
    def test(self): 
     return self.test1 

    def run(self): 
     while(1): 
      time.sleep(1) 
      self.test1 = self.test1 + 1 

ts = Test() 
ts.start() 
server = SimpleXMLRPCServer(("localhost",8888)) 
server.register_instance(ts) 
server.serve_forever() 

錯誤:

 
    File "/usr/lib/python2.7/SocketServer.py", line 225, in serve_forever 
    r, w, e = select.select([self], [], [], poll_interval) 
KeyboardInterrupt 

客戶

 
from xmlrpclib import ServerProxy 
r=ServerProxy("http://localhost:8888") 
print r.test() 
等待連接沒有錯誤或警告。在這種情況下如何斷開連接? 也許這個例子不正確?

回答

2

使用超時:

Set timeout for xmlrpclib.ServerProxy

編輯

鏈接到這裏的答案是不是與Python 2.7兼容。該作品(上W7/ActivePython的測試2.7)下面是修改後的代碼:

import xmlrpclib 
import httplib 

class TimeoutHTTPConnection(httplib.HTTPConnection): 

    def __init__(self,host,timeout=10): 
     httplib.HTTPConnection.__init__(self,host,timeout=timeout) 
     self.set_debuglevel(99) 
     #self.sock.settimeout(timeout) 

""" 
class TimeoutHTTP(httplib.HTTP): 
    _connection_class = TimeoutHTTPConnection 
    def set_timeout(self, timeout): 
     self._conn.timeout = timeout 
""" 

class TimeoutTransport(xmlrpclib.Transport): 
    def __init__(self, timeout=10, *l, **kw): 
     xmlrpclib.Transport.__init__(self,*l,**kw) 
     self.timeout=timeout 

    def make_connection(self, host): 
     conn = TimeoutHTTPConnection(host,self.timeout) 
     return conn 

class TimeoutServerProxy(xmlrpclib.ServerProxy): 
    def __init__(self,uri,timeout=10,*l,**kw): 
     kw['transport']=TimeoutTransport(timeout=timeout, use_datetime=kw.get('use_datetime',0)) 
     xmlrpclib.ServerProxy.__init__(self,uri,*l,**kw) 

if __name__ == "__main__": 
    s=TimeoutServerProxy('http://127.0.0.1:8888',timeout=2) 
    print s.test() 
+0

這不起作用希望python 2.7

 response = h.getresponse(buffering=True) AttributeError: TimeoutHTTP instance has no attribute 'getresponse' 
Bdfy 2011-04-14 16:18:03

+0

@Bdfy - 看到我編輯的答案與工作代碼 – 2011-04-14 16:58:36

0

讓您Test實例邪,退出時,主線程退出:

ts = Test() 
ts.setDaemon(True) 
ts.start() 

的問題是,爲什麼你需要將線程註冊爲XML-RPC處理程序。