python rpyc 服务器端 测试代码

 

 
  
  1. #coding:utf-8 
  2. from rpyc import Service 
  3. from rpyc.utils.server import ThreadedServer 
  4. import time,threading 
  5.  
  6. class TestService(Service): 
  7.      
  8.     def __init__(self, conn): 
  9.         self._conn = conn 
  10.         self.events={} 
  11.         print 'a conn connect:',conn 
  12.         t = threading.Thread(target = self.test_note_client, args = ()) 
  13.         t.setDaemon(True
  14.         t.start() 
  15.  
  16.     def test_note_client(self): 
  17.         print 'start on time event' 
  18.         while 1
  19.  
  20.             time.sleep(1
  21.             if 'ontime' in self.events: 
  22.                 self.events['ontime']('on time'
  23.             if 'update' in self.events: 
  24.                 self.events['update']('http://www.com'
  25.          
  26.          
  27.     def exposed_add(self, a): 
  28.          
  29.         return a+1 
  30.  
  31.     def exposed_call(self,callback):  
  32.         return callback(30
  33.  
  34.     def exposed_addlistener(self,event,callback): 
  35.         if not hasattr(self,'events'): 
  36.             self.events={} 
  37.         self.events[event]=callback 
  38.      
  39.  
  40.     def exposed_getadd(self):  
  41.         def add(a): 
  42.             print 'call on server' 
  43.             return a+1 
  44.         return add 
  45.  
  46. server = ThreadedServer(TestService, port=1235, auto_register=True
  47. server.start() 

客户端

 

 
  
  1. #coding:utf-8 
  2. from rpyc import Service 
  3. from rpyc.utils.server import ThreadedServer 
  4.  
  5. import rpyc 
  6. #各种回调的测试 
  7. while 1
  8.     try
  9.         conn = rpyc.connect('localhost'1235
  10.         task = conn.root.add(2
  11.         print task 
  12.         add=conn.root.getadd() 
  13.         print add(2
  14.  
  15.         def add_client(a): 
  16.             print 'call on client' 
  17.             return  a+1 
  18.         a=conn.root.call(add_client) 
  19.         print a,'=31?' 
  20.         def ontime_event(*args): 
  21.             print 'client on time call',args 
  22.  
  23.         conn.root.addlistener('ontime',ontime_event) 
  24.         conn.root.addlistener('update',ontime_event) 
  25.  
  26.         conn.serve_all() 
  27.     except Exception,e: 
  28.         print e 
  29.         import time 
  30.         time.sleep(1
  31.          
  32. #conn.close()