def _on_event(self, handle, data, error): if error: logger.error('Error %r happened on descriptor %d', strerror(error), self.descriptor) self._pipe.close() # notify us that we should stop os.kill(os.getpid(), signal.SIGTERM)
def inner_acceptor(handle, events, error): """Function that try to accept new connection.""" if error: # pragma: no cover logger.error( 'Error handling new connection for' ' service %r: %s', service, strerror(error)) return try: fd, addr = utils.accept_connection(listen_fd) except OSError as exc: if exc.errno not in NOTBLOCK: raise return try: # Setup socket. utils.set_nonblocking(fd) utils.set_sockopt(fd, socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) except: os.close(fd) raise handle = TCP(loop) handle.open(fd) connection = self.Connection(producer, loop, handle, addr, on_close) connections.register(connection)
def onFileOpen(self, response): error = response.error if error: print 'open fail:', errno.strerror(error), ',fd =', fd return fd = response.result self.fd = fd # fs.read(loop, fd, length, offset[, callback]) fs.read(loop, fd, self.BYTES_READ_ONCE, self.readOffset, self.onFileRead)
def onFileRead(self, response): error = response.error if error: print 'open fail:', errno.strerror(error) return result = response.result if len(result) == 0: fs.close(self.loop, self.fd) return # sys.stdout.write(result) # fs.write(loop, fd, write_data, offset[, callback]) fs.write(self.loop, 1, result, -1, self.onStdoutWrite)
def __on_connection_start(self, handler: TCP, error: Optional[int]): """ Called when the TCP connection is started :param handler: TCP Socket that is connected to the server :param error: An Error would be here if it failed to connect to the server """ if error is not None: if error == -4095: self.__logger.warning("Got End of File from server") self.shutdown() else: self.__logger.error( "Unknown TCP Error: {stringed}, errno: {no}".format( stringed=errno.strerror(error), no=error)) self.shutdown() else: self.__logger.info( "Connected to server at {ip}".format(ip=self.__ip)) # Start Asynchronous Read on the TCP Socket handler.start_read(self.__on_data) # Send the Log In Message self.__send(Connect(1, self.__username, self.__password)) self.__protocol_state = ProtocolState.IN_QUEUE
def on_connection(self, handle: TCP, error: Optional[int]): """ Called when a new user connects to the server CONCURRENT This function is called every time a new user connects, and then passes off the TCP socket to a session object which handles it asynchronously Internally, the PYUV library is using select to pick between :param handle: The TCP Server :param error: Where an error would be if there was an error connecting """ if error is not None: self.__logger.warning( "Got {error}, {errno} when client attempted to connect to server" .format(error=error, errno=errno.strerror(error))) else: new_connection = TCP(handle.loop) # Accept a connection handle.accept(new_connection) # Add it to internal connections and create a session session = self.__session_creator(new_connection) session.start() self.__connections.append(new_connection)
def inner_acceptor(handle, events, error): """Function that try to accept new connection.""" if error: # pragma: no cover logger.error('Error handling new connection for' ' service %r: %s', service, strerror(error)) return try: fd, addr = utils.accept_connection(listen_fd) except OSError as exc: if exc.errno not in NOTBLOCK: raise return try: # Setup socket. utils.set_nonblocking(fd) utils.set_sockopt(fd, socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) except: os.close(fd) raise handle = TCP(loop) handle.open(fd) connection = self.Connection(producer, loop, handle, addr, on_close) connections.register(connection)
def __on_data(self, client: TCP, data: bytes, error: Optional[int]): """ Called when the TCP socket receives data :param client: The TCP Socket that received Data :param data: Read Data :param error: An Error would be here if it failed to read data """ if error is not None: if error == -4095: self.__logger.warning("Got End of File from server") self.shutdown() else: self.__logger.error( "Unknown TCP Error: {stringed}, errno: {no}".format( stringed=errno.strerror(error), no=error)) self.shutdown() else: # Parse the Message if self.__timeout_buffer != b"": data = self.__timeout_buffer + data self.__timeout_buffer = b"" try: # Clear out the timeout buffer if self.__in_timeout: self.__timeout_timer.stop() self.__in_timeout = False while data != b"": msg = message_to_type(data).parse_and_decode(data) self.__logger.debug( "Got {message} in state {state}".format( message=msg, state=self.__protocol_state.name)) data = data[msg.calc_size() + 1:] # Dispatch to another function based on current DFA state { ProtocolState.UNAUTHENTICATED: self.__msg_on_unauthenticated, ProtocolState.IN_QUEUE: self.__msg_on_in_queue, ProtocolState.PROCESSING_GAME_STATE: self.__msg_on_processing_game_state, ProtocolState.USER_MOVE: self.__msg_on_user_move, ProtocolState.GAME_END: self.__msg_on_game_end }[self.__protocol_state](msg) except NotEnoughData: def timeout(timer_handle: Timer): self.__logger.critical( "Got invalid incomplete message ({raw}) from server, closing connections" .format(raw=self.__timeout_buffer)) self.shutdown() # If already in timeout, restart the timer if self.__in_timeout: self.__timeout_timer.stop() # Append data to the buffer self.__timeout_buffer += data # Set in timeout self.__in_timeout = True # Start timer to close connection after timeout duration if needed self.__timeout_timer.start(timeout, self.__timeout_duration, 0) except InvalidType: self.__logger.critical( "Got Invalid Message Type in message ({raw}) from server, closing connections" .format(raw=data)) self.shutdown() except StructError: self.__logger.critical( "Got Invalid Message ({raw}) from server, closing connections" .format(raw=data)) self.shutdown()
def __on_data(self, client: TCP, data: bytes, error: Optional[int]): """ Called when the session receives data :param client: The TCP socket that data was received on :param data: Raw buffer of received data :param error: Where an error would be """ if error is not None: # End of file if error == -4095: self.disconnect() else: self.__logger.warning( "Got unknown error {strerror} {errno} while reading from client {username}" .format(strerror=errno.strerror(error), errno=error, username=self.username)) self.disconnect() else: if self.__timeout_buffer != b"": data = self.__timeout_buffer + data self.__timeout_buffer = b"" try: # Clear out the timeout stuff since data was received if self.__in_timeout: self.__timeout_timer.stop() self.__in_timeout = False while data != b"": msg = message_to_type(data).parse_and_decode(data) self.__logger.debug( "Received {message} from user {user} with session in state {state}" .format(message=msg, user=self.username or "(who is not logged in)", state=self.__current_state.name)) data = data[msg.calc_size() + 1:] # Call the correct callback based on current protocol state { ProtocolState.UNAUTHENTICATED: self.__msg_on_unauthenticated, ProtocolState.IN_QUEUE: self.__msg_on_in_queue, ProtocolState.PROCESSING_GAME_STATE: self.__msg_on_processing_game_state, ProtocolState.USER_MOVE: self.__msg_on_user_move, ProtocolState.GAME_END: self.__msg_on_game_end }[self.__current_state](msg) except NotEnoughData: def timeout(timer_handle: Timer): self.__logger.critical( "Got invalid incomplete message ({raw}) from session {user}, disconnecting user" .format(raw=self.__timeout_buffer, user=self.username)) self.disconnect() # If already in timeout, restart the timer if self.__in_timeout: self.__timeout_timer.stop() # Append data to the buffer self.__timeout_buffer = data # Set in timeout self.__in_timeout = True # Start timer to close connection after timeout duration if needed self.__timeout_timer.start(timeout, self.__timeout_duration, 0) except InvalidType: self.__logger.critical( "Got Invalid Message Type in message ({raw}) from session {user}, disconnecting user" .format(raw=data, user=self.username), exc_info=True) self.disconnect() except StructError: self.__logger.critical( "Got Invalid Message ({raw}) from session {user}, disconnecting user" .format(raw=data, user=self.username)) self.disconnect()