扭曲不通过扭曲的客户端和服务器tcp传输发送整个文件

时间:2012-06-29 19:30:08

标签: python tcp twisted file-transfer

编辑:因为我通过文本附加文件没有正确保存,所以我决定重写我原来希望的方式并将文件另存为流: 扭曲的服务器:

from twisted.internet import reactor, protocol
import os,json

class Echo(protocol.Protocol):
    f = file
    def dataReceived(self, data):
        try:
            try:
                print format(json.loads(data))
                print "got jason"
                self.f=open("test.png","wb")

                self.transport.write("ready")
            except:
                print "filedata incoming!"
                self.f.write(data)
        except:
            print "unknown error" #happens if we don't receive json first

    def connectionLost(self, reason):
        if self.f!=file:self.f.close()

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

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

以下原帖

Twisted发送了99.9%的文件然后就好了,我想我写的文件不正确。

Twisted Server:

from twisted.internet import reactor, protocol
import os,json

class Echo(protocol.Protocol):

    def dataReceived(self, data):
        try:
            print format(json.loads(data))
            print "got jason"
            self.transport.write("ready")
        except:
            print "filedata incoming!"
            f = open("test.png","a")
            f.write(data)
            f.close()


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

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

Twisted Client:

from twisted.internet import reactor, protocol
import os,json

fname="pic.png"

class EchoClient(protocol.Protocol):
    """Once connected, send a message, then print the result."""

    def connectionMade(self):

        fsize = os.path.getsize(fname) 
        self.transport.write(json.dumps({"file":{"size":fsize}}))

    def sendFile(self):
        print "sending file" 
        f = open(fname,"rb")
        self.transport.write(f.read())
        f.close()
        print "closing conn"
        self.transport.loseConnection()

    def dataReceived(self, data):
        "As soon as any data is receive"
        print "Server said: ", data
        self.sendFile()


    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()

基本上服务器正在运行和监听,客户端连接并立即发送json,服务器接收数据包并告诉发送客户端'ok',然后客户端发送文件;然后服务器接收文件并将其写入磁盘。我只是测试一下,所以这个程序可能没有多大意义,特别是使用文件附加 - 但我注意到在传输和最终写入后,文件大小与原始大小差不多,但并不完全和小约300字节,因此几乎无用。 我发错文件了吗?或者只是写得不正确?哦,是的,我正在同一台计算机上测试服务器和客户端。

最终我计划向两台本地计算机发送大至1GB的文件用于备份,并希望将这些文件写成数据流,我不喜欢我正在使用的附加方法但我不喜欢我不知道如何引用文件对象而不先实际打开文件,这是我第一次收到json对象时我想要做的事情。

谢谢!

2 个答案:

答案 0 :(得分:1)

您正在打开“test.png”以附加文字。这是故意的吗?

您还有一个except,这是一个坏主意,因为它会捕获所有异常。只抓住你期望的那些例外。

答案 1 :(得分:0)

问题是您希望dataReceived一次性接收所有数据。这不是互联网的运作方式:see this Twisted FAQ for an explanation of why this is so and how to fix your code