def run(self): while not self._stop_event.is_set(): events = self._poller.poll() for fd, flag in events: if fd == self._pipe[0]: # Stop requested for client in (client for client in self.fd_map.values() if client is not self.server): self._poller.unregister(client) client.close() self.fd_map = {} break socket = self.fd_map[fd] if flag & (select.POLLIN | select.POLLPRI): # Ready to read if socket is self.server: sock, addr = socket.accept() if self.use_ssl: try: client_sock = ssl.wrap_socket(sock, server_side=True, certfile=self.cert, keyfile=self.key) except ssl.SSLError: sock.close() continue else: client_sock = sock client = self.client_cls(client_sock, self.handler) self.fd_map[client.fileno()] = client self._poller.register(client, READ_WRITE) else: data = socket.recv(1024) if data: socket.data_received(data) else: self.fd_map.pop(fd) self._poller.unregister(socket) socket.close() elif flag & select.POLLHUP: # Client hung up self.fd_map.pop(fd) self._poller.unregister(socket) socket.close() elif flag & select.POLLOUT: # Ready to send try: data = socket.write_queue.get_nowait() except Queue.Empty: pass else: if data is WSClientClose: socket.close() else: socket.send(data) elif flag & select.POLLERR: # Error self.fd_map.pop(fd) self._poller.unregister(socket) socket.close()
def run(self): while not self._stop_event.is_set(): events = self._poller.poll() for fd, flag in events: if fd == self._pipe[0]: # Stop requested for wsclient in (wsclient for wsclient in self.fd_map.values() if wsclient not in (self._socket, self._wsserver)): self._poller.unregister(wsclient) wsclient.close() self.fd_map = {} break socket = self.fd_map[fd] if flag & zmq.POLLIN: # Ready to read if socket is self._socket: data = self._socket.recv() self.websocket_broadcast(data) elif socket is self._wsserver: sock, addr = socket.accept() wsclient = WSClientSocket(sock, self.config.websocket_handler) self.fd_map[wsclient.fileno()] = wsclient self._poller.register(wsclient, READ_WRITE) else: # Data coming from a WebSocket data = socket.recv(1024) if data: socket.data_received(data) else: self.fd_map.pop(fd) self._poller.unregister(socket) socket.close() elif flag & zmq.POLLOUT: # Ready to send if isinstance(socket, WSClientSocket): try: data = socket.write_queue.get_nowait() except Queue.Empty: pass else: socket.send(data) elif flag & zmq.POLLERR: # Error self.fd_map.pop(fd) self._poller.unregister(socket) socket.close()