简体   繁体   中英

ValueError on TCP communication Python

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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