Twisted python的问题 - 发送二进制数据

时间:2009-08-04 17:02:18

标签: python file twisted send

我想要做的很简单:从客户端向服务器发送文件。首先,客户端发送有关文件的信息 - 它的大小。然后它发送实际文件。

这是我到目前为止所做的:

Server.py

from twisted.internet import reactor, protocol
from twisted.protocols.basic import LineReceiver

import pickle
import sys

class Echo(LineReceiver):

    def connectionMade(self):
        self.factory.clients.append(self)
        self.setRawMode()

    def connectionLost(self, reason):
        self.factory.clients.remove(self)

    def lineReceived(self, data):
        print "line", data

    def rawDataReceived(self, data):
            try:
                obj = pickle.loads(data)
                print obj
            except:
                print data

        #self.transport.write("wa2")

def main():
    """This runs the protocol on port 8000"""
    factory = protocol.ServerFactory()
    factory.protocol = Echo
    factory.clients = []
    reactor.listenTCP(8000,factory)
    reactor.run()

# this only runs if the module was *not* imported
if __name__ == '__main__':
    main()

Client.py

import pickle

from twisted.internet import reactor, protocol
import time
import os.path
from twisted.protocols.basic import LineReceiver

class EchoClient(LineReceiver):

    def connectionMade(self):
        file = "some file that is a couple of megs"
        filesize = os.path.getsize(file)
        self.sendLine(pickle.dumps({"size":filesize}))

        f = open(file, "rb")
        contents = f.read()
        print contents[:20]
        self.sendLine(contents[:20])
        f.close()

#        self.sendLine("hej")
#        self.sendLine("wa")

    def connectionLost(self, reason):
        print "connection lost"

class EchoFactory(protocol.ClientFactory):
    protocol = EchoClient

    def clientConnectionFailed(self, connector, reason):
        print "Connection failed - goodbye!"
        reactor.stop()

    def clientConnectionLost(self, connector, reason):
        print "Connection lost - goodbye!"
        reactor.stop()


# this connects the protocol to a server runing on port 8000
def main():
    f = EchoFactory()
    reactor.connectTCP("localhost", 8000, f)
    reactor.run()

# this only runs if the module was *not* imported
if __name__ == '__main__':
    main()

服务器只输出反序列化的对象:

{'size':183574528L}

为什么?从我想发送的文件中发生的20个字符发生了什么?

如果使用“hej”和“wa”发送,我会同时收到它们(在同一条消息中,而不是两次)。

有人?

1 个答案:

答案 0 :(得分:8)

您已使用setRawMode()将服务器设置为原始模式,因此使用传入数据(而不是lineReceived)调用回调rawDataReceived。如果您打印在rawDataReceived中收到的数据,您会看到包括文件内容在内的所有内容,但是当您调用pickle来反序列化数据时,它会被忽略。

您可以更改向服务器发送数据的方式(我建议使用netstring格式),也可以在pickle序列化对象中传递内容,并在一次调用中执行此操作。

self.sendLine(pickle.dumps({"size":filesize, 'content': contents[:20]}))