gpt4 book ai didi

python - TCP 通信 Python 上的 ValueError

转载 作者:可可西里 更新时间:2023-11-01 02:44:51 26 4
gpt4 key购买 nike

您好,我正在尝试通过 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 循环中来解决这个问题。

关于python - TCP 通信 Python 上的 ValueError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34901462/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com