简体   繁体   English

Python套接字(套接字错误坏文件描述符)

[英]Python socket (Socket Error Bad File Descriptor)

The following receiveFile() function reads a filename and file data from the socket and splits it using the delimiter $ . 以下receiveFile()函数从套接字读取文件名和文件数据,并使用分隔符$将其拆分。

But I am unable to close the socket and a Bad file descriptor error is raised. 但我无法关闭套接字并引发错误的Bad file descriptor错误。 If I comment out the self.server_socket.close() statement then there is no error but the socket is listening forever. 如果我注释掉self.server_socket.close()语句,那么没有错误,但套接字正在永远监听。

Code:- 码:-

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:- 追溯:-

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

You are closing the server's listening socket, and after that calling again accept() on it. 您正在关闭服务器的侦听套接字,然后再次调用accept()就可以了。 To finish receiving one file you should close client connection's socket (sock in function receiveFile). 要完成接收一个文件,您应该关闭客户端连接的套接字(函数receiveFile中的sock)。

in this code i am trying to shut down the server once file is received 在这段代码中,我试图在收到文件后关闭服务器

What you'll need is something to break out of the while True loop when you want to shut down the server. 当你想要关闭服务器时,你需要的是突破while True循环的东西。 A simple solution would be to exploit the exception generated when you close the server socket... 一个简单的解决方案是利用关闭服务器套接字时生成的异常...

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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM