def __init__(self, socket, io_loop=None): self.socket = socket self.io_loop = io_loop or IOLoop.instance() self.poller = zmq.Poller() self._send_queue = Queue() self._recv_callback = None self._send_callback = None self._close_callback = None self._recv_copy = False self._flushed = False self._state = self.io_loop.ERROR with stack_context.NullContext(): self.io_loop.add_handler(self.socket, self._handle_events, self._state) # shortcircuit some socket methods self.bind = self.socket.bind self.bind_to_random_port = self.socket.bind_to_random_port self.connect = self.socket.connect self.setsockopt = self.socket.setsockopt self.getsockopt = self.socket.getsockopt self.setsockopt_unicode = self.socket.setsockopt_unicode self.getsockopt_unicode = self.socket.getsockopt_unicode
def _run_callback(self, callback, *args, **kwargs): """Wrap running callbacks in try/except to allow us to close our socket.""" try: # Use a NullContext to ensure that all StackContexts are run # inside our blanket exception handler rather than outside. with stack_context.NullContext(): callback(*args, **kwargs) except: logging.error("Uncaught exception, closing connection.", exc_info=True) # Close the socket on an uncaught exception from a user callback # (It would eventually get closed when the socket object is # gc'd, but we don't want to rely on gc happening before we # run out of file descriptors) self.close() # Re-raise the exception so that IOLoop.handle_callback_exception # can see it and log the error raise
def _init_io_state(self): """initialize the ioloop event handler""" with stack_context.NullContext(): self.io_loop.add_handler(self.socket, self._handle_events, self._state)