python:rpyc获取server端对象

rpyc的client能够调用server端模块,但是会生成新的对象,怎么获取并且修改原来server端的对象?

  • rpyc_server.py

#!/usr/bin/python
# -*- coding: utf-8 -*-
from threading import Thread
from rpyc.utils.server import ThreadedServer
from rpyc.utils.classic import SlaveService
import server_func
import time


class Server(Thread):

    def run(self):
        server = ThreadedServer(SlaveService, hostname='localhost', port=9200)
        server.start()

myclass = server_func.my_class()
print myclass
if __name__ == '__main__':
    #set_var()
    s = Server()
    s.daemon = True
    s.start()
    while(True):
        myclass.print_num()
        while not server_func.rpyc_call_queue.empty():
            method, args, kargs = server_func.rpyc_call_queue.get()
            method(*args, **kargs)
  • server_func.py

#!/usr/bin/python
# -*- coding: utf-8 -*-
import time
import Queue


rpyc_call_queue = Queue.Queue()


def rpyc_call(func):
    def _(*args, **kargs):
        rpyc_call_queue.put((func, args, kargs))
    return _


class my_class(object):

    def __init__(self):
        self.a = 0

    @rpyc_call
    def print_num(self):
        print self.a
        self.a = self.a + 1
        time.sleep(1)

    @rpyc_call
    def reset(self):
        self.a = 0
        return self.a

    @rpyc_call
    def get_data(self):
        return self.a
  • rpyc_client.py

#!/usr/bin/python
# -*- coding: utf-8 -*-
import rpyc

connection = rpyc.classic.connect("localhost", 9200)
connection.modules.rpyc_server.myclass.print_num()
connection.close()

每执行一次客户端都会在服务端打印出加1的数,但是原服务端的数不受影响,但是多个客户端连接服务器修改的却是同一个对象:
图片描述

阅读 4.2k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题