我有一个非常基本的问题。客户端完全接收到了文件并关闭了连接。服务器端在关闭文件和这行read(1024)时遇到了问题。也许我把它放在错误的位置了。我想我把while循环搞糊涂了。请指导我完成这件事。下面粘贴了简单的代码
while True:
conn, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
input = raw_input("Enter 1 for accessing file and 2 for editting")
print(repr(input)) # printing input
if (input == "1"):
filename= conn.recv(1024)
f = open(filename,'rb')
l = f.read(1024)
while (1): #Keep sending it until EOF id found
conn.send(l) #Keep sending the opened file
print(repr(l))
l = f.read(1024)
f.close()发布于 2016-06-20 20:09:22
在您的while循环中,您将关闭该文件,并在下一个循环周期中尝试读取该文件,因此您会得到错误I/O operation on closed file。除了放错位置的f.close()之外,您的循环还缺少一个中断条件。更好地替换
l = f.read(1024)
while (1): #Keep sending it until EOF id found
conn.send(l) #Keep sending the opened file
print(repr(l))
l = f.read(1024)
f.close()使用
for l in iter(lambda: f.read(1024), ''): #Keep sending it until EOF id found
conn.send(l) #Keep sending the opened file
conn.close()
f.close()https://stackoverflow.com/questions/37241746
复制相似问题