python select方法卡住了

时间:2015-05-16 13:21:21

标签: python select

我正在尝试在python中创建一个多客户端https服务器。为了获得端口80和443中的连接,我使用select两次。由于某些原因,当我第二次使用select时程序被卡住(我通过在选择之前和之后的行上打印一些东西来检查)。在main方法中,我创建了一个ConnectionHandler对象,并在循环中使用handle_connections。以下是ConnectionHandler的重要部分(我在handle_connections中使用select)。另外,因为我还在编写程序的其余部分,所以我现在还没有真正使用https连接,所以请忽略那些"错误"。如何让它工作?

class ConnectionHandler:
    def __init__(self):
        self.open_http_sockets = []
        self.open_https_sockets = []
        self.settings = MemoryHandler.get_server_settings()
        self.http_socket = socket.socket()
        self.http_socket.bind((self.settings['http_ip'], int(self.settings['http_port'])))
        self.http_socket.listen(10)
        self.https_socket = socket.socket()
        self.https_socket.bind((self.settings['https_ip'], int(self.settings['https_port'])))
        self.https_socket.listen(10)


    def handle_connections(self):
        rlist, wlist, xlist = select.select([self.http_socket] + self.open_http_sockets, [], [])
        for socket in rlist:
            if socket is self.http_socket:
                # handle the server http socket
                client, address = socket.accept()
                print 'new connection ' + address[0]
                self.open_http_sockets.append(client)
            else:
                # handle all other http sockets
                self.http_communication(socket)
        #the problem is here
        rlist, wlist, xlist = select.select([self.https_socket] + self.open_https_sockets, [], [])
        for socket in rlist:
            if socket is self.https_socket:
                # handle the server https socket
                client, address = socket.accept()
                self.open_https_sockets.append(client)
            else:
                # handle all other https sockets
                self.https_communication(socket)

1 个答案:

答案 0 :(得分:0)

通常,select被放入一个循环中。 select阻止程序直到事件发生。因此,如果第一个循环成功,那么第二个循环将开始,但不会参加正常的http连接。

我建议您进行一次选择,并在if中包含httphttps个连接。

类似的东西:

for socket in rlist:
    if socket is self.http_socket:
        client, address = socket.accept()
        print 'new connection ' + address[0]
        self.open_http_sockets.append(client)
    elif socket is self.https_socket:
        # handle the server https socket
        client, address = socket.accept()
        self.open_https_sockets.append(client)
    else:
        # handle all other sockets
        self.http_communication(socket)