簡體   English   中英

Twisted python的問題 - 發送二進制數據

[英]Problem with Twisted python - sending binary data

我想要做的很簡單:從客戶端向服務器發送文件。 首先,客戶端發送有關文件的信息 - 它的大小。 然后它發送實際文件。

這是我到目前為止所做的:

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”發送,我會得到它們(在同一個消息中,而不是兩次)。

有人?

您已使用setRawMode()將服務器設置為原始模式,因此使用傳入數據(而不是lineReceived)調用回調rawDataReceived。 如果您打印在rawDataReceived中收到的數據,您會看到包括文件內容在內的所有內容,但是當您調用pickle來反序列化數據時,它會被忽略。

您可以更改向服務器發送數據的方式(我建議使用netstring格式),也可以在pickle序列化對象中傳遞內容,並在一次調用中執行此操作。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM