1

Hi i am trying to send encrypted files over TCP. When run server and send some file everything works fine, but when i try to send once again i get this error on server side:

Traceback (most recent call last):
File "server.py", line 38, in <module>
    f.write(l)
ValueError: I/O operation on closed file

I am new with TCP communication so i am not sure why is file closed.

server code:

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                 # Reserve a port for your service.
s.bind((host, port))        # Bind to the port

f = open('file.enc','wb')
s.listen(5)                 # Now wait for client connection.
while True:
    c, addr = s.accept()     # Establish connection with client.
    print 'Got connection from', addr
    print "Receiving..."
    l = c.recv(1024)
    while (l):
        print "Receiving..."
        f.write(l)
        l = c.recv(1024)
    f.close()
    print "Done Receiving"
    decrypt_file('file.enc', key)
    os.unlink('file.enc')
    c.send('Thank you for connecting')
    c.close()                # Close the connection

client code:

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                 # Reserve a port for your service.
print '[1] send image'
choice = input('choice: ')

if choice == 1:
    encrypt_file('tosendpng.png', key)
    #decrypt_file('to_enc.txt.enc', key)

    s.connect((host, port))
    f = open('tosendpng.png.enc','rb')
    print 'Sending...'
    l = f.read(1024)
    while (l):
        print 'Sending...'
        s.send(l)
        l = f.read(1024)
    f.close()
    print "Done Sending"
    os.unlink('tosendpng.png.enc')
    s.shutdown(socket.SHUT_WR)
    print s.recv(1024)
    s.close()                     # Close the socket when done

2 Answers 2

3

Your problem is acutally not related to sockets, as far as I can tell.

You open the file f before your while loop, but you close it inside of the loop. Thus, the second time you try to write to f it is closed. That's also exactly what the error tells you.

Try moving f = open('file.enc','wb') into the while loop to fix this problem.

Sign up to request clarification or add additional context in comments.

Comments

2

The problem is completely unrelated to TCP, your code is

f = open('file.enc','wb')
while True:
    ...    
    f.write(l)
    ...
    f.close()
    ...

The first connection will work fine, but during it the file gets closed. Move f = open('file.enc','wb') inside the while True loop to open the file anew upon every request.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.