简体   繁体   English

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

[英]twisted not sending entire file with twisted client and server tcp transfer

Edit: since I was appending via text the file was not being saved properly, I decided to rewrite the way I originally was hoping to and save the file as a stream instead: Twisted server: 编辑:由于我是通过文本追加文件的,因此未正确保存,因此我决定重写我最初希望的方式并将文件另存为流:Twisted服务器:

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

original post below 下面的原始帖子

Twisted sends like 99.9% of the file and then that seems to be it, I'm thinking I am writing the file incorrectly. 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()

Basically the server is running and listening, the client connects and immediately sends json, server receives packet and tells send client the 'ok', the client then sends the file; 基本上,服务器正在运行并正在侦听,客户端连接并立即发送json,服务器接收数据包并告知发送客户端“确定”,然后客户端发送文件。 then the server receives the file and writes it to disk. 然后服务器接收文件并将其写入磁盘。 I'm just testing things out so this program might not make much sense, especially the use of file append-- but I noticed that after the transfer and final write the file is just about the same size as the original, but not quite and is smaller by about 300 bytes and therefore just about useless. 我只是测试一下东西,所以该程序可能没有多大意义,尤其是使用文件附加-但我注意到,在传输和最终写入之后,该文件的大小与原始文件大小几乎相同,但并不完全相同。小于300字节,因此几乎没有用。 Am I sending the file incorrectly? 我发送的文件不正确吗? Or just writing it incorrectly? 还是只是写错了? Oh yea, I'm testing the server and client on the same computer. 哦,是的,我正在同一台计算机上测试服务器和客户端。

Ultimately I plan on sending files as large as 1GB to and from two local computers for backup purposes and want the files to be written as a stream of data, I don't like the append method I'm using but I don't know how to reference the file object without actually opening the file first, and that's something I only want to do when I first receive the json object. 最终,我计划在两台本地计算机之间来回发送最大1GB的文件,以进行备份,并且希望将这些文件作为数据流写入,我不喜欢我使用的append方法,但是我不知道如何在不首先实际打开文件的情况下引用文件对象,而这是我第一次收到json对象时只想做的事情。

Thanks! 谢谢!

You're opening "test.png" for appending text. 您正在打开“ test.png”以添加文本。 Is that intentional? 那是故意的吗?

You also have a bare except , which is a bad idea because it catches all exceptions. 您也有一个裸露的except ,这是一个坏主意,因为它捕获了所有异常。 Catch only those exceptions you expect. 仅捕获您期望的那些异常。

The problem is that you're expecting all your data to be received at once by dataReceived . 问题是您期望dataReceived一次接收所有数据。 That's not how the Internet works: see this Twisted FAQ for an explanation of why this is so and how to fix your code . 这不是Internet的工作方式: 请参阅Twisted FAQ,以获取有关为何如此以及如何修复代码的解释

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM