我正在尝试在 Perspective Broker 中实现一个简单的服务器回复。
可能的实施(如果可能,请建议其他人):
客户端请求服务器执行服务器方法,服务器执行然后回复(通过执行客户端方法,其唯一目的是打印消息):
[Client-side]:
class ClientPrint(pb.Referenceable):
def remote_clientprint(self, message):
print "Printing the message from the server: ", message
[Server-side]:
class RootServerObject(pb.Root):
def remote_OneFunc(self, ...):
...
print "Now sending the reply..."
*get ClientPrint object?*
clientprintobj.callRemote("clientprint", "this is the reply!")
如何实现客户端对象的抓取?有没有比抓取客户端对象并调用仅打印客户端方法更好的方法来实现服务器回复?
这是我尝试实现回复的完整代码:
[客户端]:
from twisted.internet import reactor
from twisted.spread import pb
class Client():
def __init__(self, addr, port, spec):
self.addr = None
self.port = None
self.SomeData = None
def connect(self, addr, port):
factory = pb.PBClientFactory()
reactor.connectTCP(addr, port, factory)
def1 = factory.getRootObject()
def1.addCallbacks(self.got_obj, self.err_obj)
def got_obj(self, rootsrvobj):
print "Got root server obj:", rootsrvobj
self.server = rootsrvobj
def2 = self.server.callRemote("SomeFunc", SomeData)
def err_obj(self, reason):
print "Error getting root server obj:", reason
self.quit()
def cmdsub(addr, port, SomeData):
c = Client(addr, port, SomeData)
c.connect(addr, port)
[服务器端]:
class RootServerObject(pb.Root):
def __init__(self):
self.DataOut = None
def remote_SomeFunc(self, SomeData):
self.DataOut = hash(SomeData)
print "Now sending reply..."
*implement a reply?*
也许有一些更高级的 Twisted(或 Twisted PB)特性可以让这变得更简单。
文档:https ://twistedmatrix.com/documents/12.3.0/core/howto/pb-usage.html#auto3
谢谢。