在python中捕获一个损坏的套接字

时间:2010-10-25 16:52:04

标签: python sockets

当发生损坏的管道异常时,我在检测到损坏的套接字时遇到问题。请参阅以下代码以获取示例:

服务器:

import errno, select, socket, time, SocketServer

class MetaServer(object):
    def __init__(self):
        self.server = Server(None, Handler, bind_and_activate=False)
    def run(self, sock, addr):
        rfile = sock.makefile('rb', 1)
        self.server.process_request(sock, addr)
        while 1:
            r, _, _ = select.select([rfile], [], [], 1.0)
            if r:
                print 'Got %s' % rfile.readline()
            else:
                print 'nothing to read'

class Server(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    allow_reuse_address = True
    daemon_threads = True

class Handler(SocketServer.StreamRequestHandler):
    def handle(self):
        print 'connected!'
        try:
            while 1:
                self.wfile.write('testing...')
                time.sleep(1)
        except socket.error as e:
            if e.errno == errno.EPIPE:
                print 'Broken pipe!'
        self.finish()
        self.request.close()

if __name__ == '__main__':
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('127.0.0.1', 8081))
    s.listen(5)
    ms = MetaServer()
    while 1:
        client, address = s.accept()
        ms.run(client, address)

客户:

import select, socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 8081))
while 1:
    r, _, _ = select.select([s], [], [], 1.0)
    if not r:
        continue
    msg = s.recv(1024)
    print 'Got %s' % (msg,)

现在,如果我运行服务器和客户端,一切都很好,我每秒钟都会收到“无法读取”消息。一旦我将CTRL-C移出客户端,服务器就会疯狂并开始从应该是一个被破坏的套接字“读取”,抛弃大量的“获取”消息。

有没有办法在MetaServer.run()函数中检测这个损坏的套接字以避免上述行为?

1 个答案:

答案 0 :(得分:3)

是的,这是文档中没有的东西,但是旧的Un * x行为:当你得到一个空字符串时需要中止。