TCP通信Python上的值错误

2024-09-30 01:37:16 发布

您现在位置: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通信,所以我不知道为什么关闭文件。在

服务器代码:

^{pr2}$

客户代码:

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

Tags: 文件代码服务器sendhostpngportsocket
2条回答

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

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

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

据我所知,你的问题完全与插座无关。在

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

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

相关问题 更多 >

    热门问题