質問

私がやろうとしていることはかなり簡単です。ファイルをクライアントからサーバーに送信します。最初に、クライアントはファイルに関する情報、つまりファイルのサイズを送信します。次に、実際のファイルを送信します。

これは私がこれまでにやったことです:

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」代わりに送信し、両方を取得します(2回ではなく、同じメッセージで)。

誰か?

役に立ちましたか?

解決

setRawMode()を使用してサーバーをrawモードに設定しているため、コールバックrawDataReceivedが着信データ(lineReceivedではない)で呼び出されています。 rawDataReceivedで受け取ったデータを印刷すると、ファイルの内容を含むすべてが表示されますが、pickleを呼び出してデータを逆シリアル化すると、無視されます。

データをサーバーに送信する方法を変更するか(netstring形式をお勧めします)、またはpickleシリアル化オブジェクト内でコンテンツを渡し、1回の呼び出しでこれを行います。

self.sendLine(pickle.dumps({"size":filesize, 'content': contents[:20]}))
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top