TCP通信Python上的ValueError

时间:2016-01-20 13:32:34

标签: python sockets tcp communication

您好我正在尝试通过TCP发送加密文件。 当运行服务器并发送一些文件时一切正常,但当我再次尝试发送时,我在服务器端收到此错误:

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

我是TCP通信的新手,所以我不确定为什么要关闭文件。

服务器代码:

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

客户代码:

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 个答案:

答案 0 :(得分:3)

据我所知,你的问题实际上与套接字无关。

f循环之前打开文件while,但是在循环内部关闭它。因此,第二次尝试写入f时,它将被关闭。这也正是错误告诉你的。

尝试将f = open('file.enc','wb')移至while循环以解决此问题。

答案 1 :(得分:2)

问题与TCP完全无关,您的代码是

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

第一个连接可以正常工作,但在此期间文件将被关闭。在f = open('file.enc','wb')循环内移动while True以在每次请求时重新打开文件。