这里有2个程序,一个实现了server端的远程加法协议,另外的一个作为客户端。第一个例子使用的是unauthenticated Tub,所以不需要手动从服务端拷贝FURL到客户端。2个程序都是单独的程序,但一般来讲,你应该创建一个应用并传递文件到twistd-noy。下面展示的是没有authenticated的例子:
listings/pblserver.py服务器程序:
from twisted.internet import reactor
from foolscap.api import Referenceable, UnauthenticatedTub
class MathServer(Referenceable):
def remote_add(self, a, b):
return a+b
def remote_subtract(self, a, b):
return a-b
myserver = MathServer()
tub = UnauthenticatedTub()
tub.listenOn(“tcp:12345”)
tub.setLocation(“localhost:12345”)
url = tub.registerReference(myserver, “math-service”)
print “the object is available at:”, url
tub.startService()
reactor.run()
[listings/pblclient.py]客户端程序:
from twisted.internet import reactor
from foolscap.api import UnauthenticatedTub
def gotErr1(why):
print “unable to get the RemoteReference:”, why
reactor.stop()
def gotErr2(why):
print”unable to invoke the remote method:”, why
reactor.stop()
def gotReference(remote):
print “got a RemoteReference”
print “asking it to add 1+2”
d = remote.callRemote(“add”, a=1, b=2)
d .addCallbacks(gotAnswer, gotErr2)
def gotAnswer(answer):
print “the answer is”, answer
reactor.stop()
tub = UnauthenticatedTub()
tub.startService()
d = tub.getReference(“pbu://localhost:12345/math-service”)
d.addCallbacks(gotReference, gotErr1)
reactor.run()
调试问题:
1) 由于目标计算机积极拒绝
Ok,是由于以下的原因:
将tub.listenOn(“tcp:12345”)写成tub.listenOn(“tcp:1234”)导致该错误
下面的是authenticated例子:
listings/pb2server.py服务器程序:
from twisted.internet import reactor
from foolscap import crypto
from foolscap.api import Referenceable, Tub
class MathServer(Referenceable):
def remote_add(self, a, b):
return a+b
def remote_subtract(self, a, b):
return a-b
myserver = MathServer()
tub = Tub(certFile=”pb2server.pem”)
tub.listenOn(“tcp:12345”)
tub.setLocation(“localhost:12345”)
url = tub.registerReference(myserver, “math-service”)
print “the object is available at:”, url
tub.startService()
reactor.run()
[listings/pb2client.py]客户端程序:
import sys
from twisted.internet import reactor
from foolscap.api import Tub
def gotErr1(why):
print “unable to get the RemoteReference:”, why
reactor.stop()
def gotErr2(why):
print”unable to invoke the remote method:”, why
reactor.stop()
def gotReference(remote):
print “got a RemoteReference”
print “asking it to add 1+2”
d = remote.callRemote(“add”, a=1, b=2)
d .addCallbacks(gotAnswer, gotErr2)
def gotAnswer(answer):
print “the answer is”, answer
reactor.stop()
if len(sys.argv) < 2:
print “Usage: pb2client.py URL”
sys.exit(1)
url = sys.argv[1]
tub = Tub()
tub.startService()
d = tub.getReference(url)
d.addCallbacks(gotReference, gotErr1)
reactor.run()
问题:
1)no module named OpenSSL
安装openssl:http://pypi.python.org/pypi/pyOpenSSL下载pyOpenSSL-0.13.winxp32-py2.7.exe (md5)(根据自己的版本来决定)