简体   繁体   English

Asyncore TCP服务器,我不了解客户端套接字如何关闭连接

[英]Asyncore TCP server, I not understand how connection close for client socket

I not understand how connection close for client socket. 我不了解客户端套接字的连接如何关闭。

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

If I rewrite removeClient method in TCPServer 如果我在TCPServer重写removeClient方法

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

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

PS sorry for my english PS对不起我的英语


UPD: Dirty hack 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)

:) It's work! :) 是工作!

That right. 没错 Thanks everybody 谢谢大家

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM