嗨,我正在尝试通过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
这个问题与TCP完全无关,您的代码是
第一个连接可以正常工作,但在此期间文件将关闭。将
f = open('file.enc','wb')
移到while True
循环中,以便在每次请求时重新打开该文件。在据我所知,你的问题完全与插座无关。在
在
while
循环之前打开文件f
,但在循环内部关闭它。因此,第二次尝试写入f
时,它将关闭。这也是错误告诉你的。在尝试将
f = open('file.enc','wb')
移到while
循环中以解决此问题。在相关问题 更多 >
编程相关推荐