TCP 通信的 ValueError Python

ValueError on TCP communication Python

您好,我正在尝试通过 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

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

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

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

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

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

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