Asyncore TCP服务器,我不明白如何连接客户端套接字

时间:2013-02-06 12:44:30

标签: python sockets asyncore

我不明白客户端套接字的连接是如何关闭的。

import asyncore
import socket

class TCPClientHandle(asyncore.dispatcher):
    def __init__(self, sock, server):
        asyncore.dispatcher.__init__(self, sock)
        self.server = server

    .....

    def handle_close(self):
        print 'Client: handle_close'
        self.server.removeClient(self)

class TCPServer(asyncore.dispatcher, dict):
    def __init__(self, host='127.0.0.1', port=31337):
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        dict.__init__(self, {self.fileno(): self})
        self.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.bind((host, port))
        self.listen(5)

    def handle_accept(self):
        print 'Server: handle_accept'
        client, (host, port,) = self.accept()

        print 'Новый клиент %s:%d' % (host, port,)
        self[client.fileno()] = TCPClientHandle(client, self)

    def removeClient(self, client):
        print 'Server: removeClient'
        del self[client.fileno()]

def main():
    asyncore.loop(0.1, True, TCPServer('127.0.0.1'))

if __name__ == '__main__':
    main()

如果我在removeClient

中重写TCPServer方法
def removeClient(self, client):
    print 'Server: removeClient'
    del self[client.fileno()]
    client.close()

我有错误socket.error: [Errno 9] Bad file descriptor

对不起我的英文


UPD: 肮脏的黑客

class TCPServer(asyncore.dispatcher, dict):
    doDel = []
    ....
    def handle_accept(self):
        print 'Server: handle_accept'
        client, (host, port,) = self.accept()
        print 'Новый клиент %s:%d' % (host, port,)
        self[client.fileno()] = TCPClientHandle(client, self)
        if len(self.doDel) >= 5:
            self.doDel.pop().close()

    ....

    def removeClient(self, client):
        print 'Server: removeClient'
        del self[client.fileno()]
        self.doDel.insert(0, client)

:)这是工作!

1 个答案:

答案 0 :(得分:1)

那是对的。谢谢大家

class TCPClientHandle(asyncore.dispatcher_with_send):
    def __init__(self, sock, server):
        asyncore.dispatcher.__init__(self, sock)
        self.server = server

    .....

    def handle_close(self):
        if self.server.removeClient(self):
            self.close()

class TCPServer(asyncore.dispatcher, dict):
    .....
    def removeClient(self, client):
        del self[client.fileno()]
        return True