Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8158573
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T17:38:52+00:00 2026-06-06T17:38:52+00:00

Edit: since I was appending via text the file was not being saved properly,

  • 0

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:

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 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; 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.
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.

Thanks!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-06T17:38:54+00:00Added an answer on June 6, 2026 at 5:38 pm

    You’re opening “test.png” for appending text. Is that intentional?

    You also have a bare except, which is a bad idea because it catches all exceptions. Catch only those exceptions you expect.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

EDIT : I completely re-wrote the question since it seems like I was not
Edit Since there were many downvotes and people who didn't understand what I'm asking
Edit: I've learned much since the posting of this question, and so I have
Edit (2012-04-12): Since this question was asked it is now possible (as of jQuery
EDIT: This question is now redundant since Twitter no longer supports basic auth. I've
I'm solving UVA's Edit Step Ladders on an uva sub-site named programming-challenges.com, but since
What's a quick'n easy way to add edit function to static HTML? I could
EDIT: Since you are asking for specifics, consider a photo-sharing site (like Flickr or
EDIT: Please note that I am appending my original question with my actual question
EDIT 07/14 As Bill Burgess mentionned in a comment of his answer, this question

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.