Python 套接字(套接字错误错误文件描述符)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16382899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python socket (Socket Error Bad File Descriptor)
提问by Ali Ahmad
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 descriptorerror is raised. If I comment out the self.server_socket.close()statement then there is no error but the socket is listening forever.
但我无法关闭套接字并Bad file descriptor引发错误。如果我注释掉该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
采纳答案by Nickolay Olshevsky
You are closing the server's listening socket, and after that calling again accept() on it. To finish receiving one file you should close client connection's socket (sock in function receiveFile).
您正在关闭服务器的侦听套接字,然后再次调用其上的 accept() 。要完成接收一个文件,您应该关闭客户端连接的套接字(函数receiveFile 中的sock)。
回答by Aya
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 Trueloop when you want to shut down the server. A simple solution would be to exploit the exception generated when you close the server socket...
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'

