2016-05-15 57 views
0

我有一个非常基本的问题。客户端完全接收文件并关闭连接。服务器端只是在关闭文件和读取(1024)行时遇到问题。也许我把它放在错误的位置上。我猜想我在while循环中感到困惑。请通过这个指导我。简单的代码粘贴下面关闭文件的I/O操作(缩进问题)Python-Sockets

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() 

回答

0

在你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()