我正在用 Python 实现一个服务器。我一直在关注 Doug Hellmann's blog 上的教程:
我有一个问题,select()
没有捕捉到破损或关闭的管道。
# Create socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Non blocking socket
serversocket.setblocking(0)
# Bind socket
serversocket.bind((HOST, PORT))
# Socket listening
serversocket.listen(5)
# Sockets from which we expect to read
inputs = [ serversocket ]
# Sockets to which we expect to write
outputs = [ ]
resign = re.compile("resign")
while inputs:
print "Waiting for connection..."
readable, writable, exceptional = select.select(inputs, outputs, inputs)
for s in exceptional:
print >>sys.stderr, 'handling exceptional condition for', s.getpeername()
# Stop listening for input on the connection
inputs.remove(s)
s.close()
for s in readable:
# SERVER LISTENS TO CONNEXION
if s is serversocket:
if some_stuff_is_true:
connection, client_address = s.accept();
print 'New connection from ', client_address
connection.setblocking(0)
inputs.append(connection)
# CLIENT READABLE
else:
data = s.recv(MAXLINE)
#If socket has data to be read
if data:
print data # Test if data correclty received
if resign.findall(data):
inputs.remove(s)
s.close()
客户端正常关闭socket时,不被select捕获,客户端断开socket时,不被`exceptional捕获。
如何使该服务器对关闭/损坏的套接字具有鲁棒性?
最佳答案
当远程端完全关闭套接字时,它将对您变得“可读”。当您调用 recv()
时,您将返回零 个字节。您的代码不会在 if data:
的 else:
子句中执行任何操作。这是您应该放置对关闭的套接字作出 react 的代码的地方。
关于Python - select() 没有捕捉到损坏的套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13257047/