今天写了一个twisted例程,很顺利,twisted的确不错。但是在调试def dataReceived(self,data):的时候,突然想到,如果data参数需要传入二进制数据怎么办,于是google一下,无果。后来想了一下,会不会像php一样不管string和binary都当作字符串处理?毕竟都是弱类型。
于是,就写了两段代码,一个服务端,一个客户端。他们的工作是,客户端读取一个图片文件的数据,然后发送到服务器端,服务器端原样返回,然后客户端再把返回的数据存到另一个图片里面,看看,存入的图片对不对(由于没有写buffer,所以你要试验的话,尽量找个小图片,否则,可能会存下半张图片),结果不出我所料,和php一样string和binary不分的,就是客户端发送过去的是string服务端就当字符串处理,如果发过去的是binary就当binary处理(python有个struct模块 专门处理二进制数据,和php的pack、unpack是 函数一样的,连函数名都一样,不知道谁抄谁的) 。
下面是server端代码:
from twisted.internet import reactor, defer, protocol
from twisted.internet.protocol import Protocol
class DeferFactory(protocol.ServerFactory):
def __init__(self):
self.deferred = defer.Deferred();
class Piper(Protocol):
def connectionMade(self):
self.transport.write("An apple a day keeps the doctor away\r\n");
#self.factory.deferred.callback(self);
def dataReceived(self,data):
self.transport.write(data);
#self.factory.deferred.callback((self, data));
def testcallback(data):
data[0].transport.write(data[1]);
#factory.deferred.callback
#This can only be run once.
#Later calls to this or errback will raise twisted.internet.defer.AlreadyCalledError.
#so redefine this
data[0].factory.deferred=defer.Deferred();
data[0].factory.deferred.addCallback(testcallback);
if __name__ == "__main__":
factory = DeferFactory();
factory.protocol = Piper;
factory.deferred.addCallback(testcallback);
reactor.listenTCP(8007,factory);
reactor.run();
然后是client端:
# connectiontest.py
from twisted.internet import reactor, defer, protocol
class CallbackAndDisconnectProtocol(protocol.Protocol):
def connectionMade(self):
self.factory.deferred.callback("Connected!");
def dataReceived(self,data):
if(data.find("apple") > 0):
myfile = file("C:\\fish.jpg", "rb");
self.transport.write(myfile.read());
myfile.close()
else:
myfile = open("C:\\fish2.jpg", "wb");
myfile.write(data)
myfile.close()
self.transport.loseConnection()
reactor.stop()
class ConnectionTestFactory(protocol.ClientFactory):
protocol = CallbackAndDisconnectProtocol
def __init__(self):
self.deferred = defer.Deferred()
def clientConnectionFailed(self, connector, reason):
self.deferred.errback(reason)
def testConnect(host, port):
testFactory = ConnectionTestFactory()
reactor.connectTCP(host, port, testFactory)
return testFactory.deferred
def handleSuccess(result, port):
print "Connected to port %i" % port
#reactor.stop( )
def handleFailure(failure, port):
print "Error connecting to port %i: %s" % (port, failure.getErrorMessage())
reactor.stop()
if __name__ == "__main__":
#import sys
#if not len(sys.argv) == 3:
# print "Usage: connectiontest.py host port"
# sys.exit(1)
#host = sys.argv[1]
#port = int(sys.argv[2])
#connecting = testConnect(host, port)
#connecting.addCallback(handleSuccess, port)
#connecting.addErrback(handleFailure, port)
connecting = testConnect("localhost", 8007)
connecting.addCallback(handleSuccess, 8007)
connecting.addErrback(handleFailure, 8007)
reactor.run( )