【问题标题】:Asyncore TCP server, I not understand how connection close for client socketAsyncore TCP 服务器,我不明白如何关闭客户端套接字的连接
【发布时间】:2013-03-01 12:41:37
【问题描述】:

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

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()

如果我在TCPServer 中重写removeClient 方法

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

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

P.S 对不起我的英语


更新: 肮脏的黑客

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)

:) 成功了!

【问题讨论】:

    标签: python sockets asyncore


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2018-05-24
      • 1970-01-01
      • 2013-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多