15

以下receiveFile()函数从套接字读取文件名和文件数据,并使用分隔符将其拆分$

但我无法关闭套接字并Bad file descriptor引发错误。如果我注释掉该self.server_socket.close()语句,则没有错误,但套接字一直在监听。

代码:-

def listen(self):
    self.server_socket.listen(10)
    while True:
        client_socket, address = self.server_socket.accept()
        print 'connected to', address
        self.receiveFile(client_socket)



def receiveFile(self,sock):
    data = sock.recv(1024)
    data = data.split("$");
    print 'filename', data[0]
    f = open(data[0], "wb")
    #data = sock.recv(1024)
    print 'the data is', data[1]
    f.write(data[1])
    data = sock.recv(1024)
    while (data):
        f.write(data)
        data=sock.recv(1024)
    f.close()
    self.server_socket.close()
    print 'the data is', data
    print "File Downloaded"

追溯:-

Traceback (most recent call last):
  File "server.py", line 45, in <module>
    a = Server(1111)
  File "server.py", line 15, in __init__
    self.listen()
  File "server.py", line 20, in listen
    client_socket, address = self.server_socket.accept()
  File "c:\Python27\lib\socket.py", line 202, in accept
    sock, addr = self._sock.accept()
  File "c:\Python27\lib\socket.py", line 170, in _dummy
    raise error(EBADF, 'Bad file descriptor')
socket.error: [Errno 9] Bad file descriptor
4

2 回答 2

12

您正在关闭服务器的侦听套接字,然后再次调用 accept() 。要完成接收一个文件,您应该关闭客户端连接的套接字(函数 receiveFile 中的 sock)。

于 2013-05-05T09:16:45.390 回答
4

在这段代码中,我试图在收到文件后关闭服务器

while True当您想关闭服务器时,您需要一些东西来打破循环。一个简单的解决方案是利用关闭服务器套接字时产生的异常......

def listen(self):
    self.server_socket.listen(10)
    while True:
        try:
            client_socket, address = self.server_socket.accept()
        except socket.error:
            break
        print 'connected to', address
        self.receiveFile(client_socket)
    print 'shutting down'
于 2013-05-05T09:20:57.973 回答