Handle incoming packet from server.
420718
def _process(self, data_buffer):
        
        packet = json.loads(data_buffer.decode('utf-8'))

        if packet['cmd'] == 'out':
            # Call os.write manually. In Python2.6, sys.stdout.write doesn't use UTF-8.
            os.write(sys.stdout.fileno(), packet['data'].encode('utf-8'))

        elif packet['cmd'] == 'suspend':
            # Suspend client process to background.
            if hasattr(signal, 'SIGTSTP'):
                os.kill(os.getpid(), signal.SIGTSTP)

        elif packet['cmd'] == 'mode':
            # Set terminal to raw/cooked.
            action = packet['data']

            if action == 'raw':
                cm = raw_mode(sys.stdin.fileno())
                cm.__enter__()
                self._mode_context_managers.append(cm)

            elif action == 'cooked':
                cm = cooked_mode(sys.stdin.fileno())
                cm.__enter__()
                self._mode_context_managers.append(cm)

            elif action == 'restore' and self._mode_context_managers:
                cm = self._mode_context_managers.pop()
                cm.__exit__()
549574
def handle_get_request(self, environ, start_response):
        """"""
        connections = [
            s.strip()
            for s in environ.get('HTTP_CONNECTION', '').lower().split(',')]
        transport = environ.get('HTTP_UPGRADE', '').lower()
        if 'upgrade' in connections and transport in self.upgrade_protocols:
            self.server.logger.info('%s: Received request to upgrade to %s',
                                    self.sid, transport)
            return getattr(self, '_upgrade_' + transport)(environ,
                                                          start_response)
        try:
            packets = self.poll()
        except exceptions.QueueEmpty:
            exc = sys.exc_info()
            self.close(wait=False)
            six.reraise(*exc)
        return packets
1099913
protected void handlePacket(IncomingPacket incomingPacket) {
    String typeName = incomingPacket.unpackString();
    REQID rid = incomingPacket.unpackREQID();
    if (contextMap.containsKey(rid)) {
      // This incomingPacket contains the response of Request
      Object ctx = contextMap.get(rid);
      Message.Builder bldr = responseMessageMap.get(rid);
      contextMap.remove(rid);
      responseMessageMap.remove(rid);
      incomingPacket.unpackMessage(bldr);
      // Call onResponse to handle it
      if (bldr.isInitialized()) {
        Message response = bldr.build();
        onResponse(StatusCode.OK, ctx, response);
        return;
      } else {
        onResponse(StatusCode.INVALID_PACKET, ctx, null);
        return;
      }
    } else if (rid.equals(REQID.zeroREQID)) {
      // If rid is REQID.zeroREQID, this is a Message, e.g. no need send back response.
      // Convert it into message and call onIncomingMessage() to handle it
      Message.Builder bldr = messageMap.get(typeName);
      if (bldr != null) {
        bldr.clear();
        incomingPacket.unpackMessage(bldr);
        if (bldr.isInitialized()) {
          onIncomingMessage(bldr.build());
        } else {
          // We just need to log here
          // TODO:- log
        }
      } else {
        // We got a message but we didn't register
        // TODO:- log here
      }
    } else {
      // This might be a timeout response
      // TODO:- log here
    }
  }
65016
def handle(self, pkt, raddress, rport):
        """"""
        if not self.context.tidport:
            self.context.tidport = rport
            log.info("Set remote port for session to %s" % rport)

        # Now check the packet type and dispatch it properly.
        if isinstance(pkt, TftpPacketOACK):
            log.info("Received OACK from server")
            try:
                self.handleOACK(pkt)
            except TftpException as err:
                log.error("Failed to negotiate options: %s" % str(err))
                self.sendError(TftpErrors.FailedNegotiation)
                raise
            else:
                log.debug("Sending ACK to OACK")

                self.sendACK(blocknumber=0)

                log.debug("Changing state to TftpStateExpectDAT")
                return TftpStateExpectDAT(self.context)

        elif isinstance(pkt, TftpPacketDAT):
            # If there are any options set, then the server didn't honour any
            # of them.
            log.info("Received DAT from server")
            if self.context.options:
                log.info("Server ignored options, falling back to defaults")
                self.context.options = { 'blksize': DEF_BLKSIZE }
            return self.handleDat(pkt)

        # Every other packet type is a problem.
        elif isinstance(pkt, TftpPacketACK):
            # Umm, we ACK, the server doesn't.
            self.sendError(TftpErrors.IllegalTftpOp)
            raise TftpException("Received ACK from server while in download")

        elif isinstance(pkt, TftpPacketWRQ):
            self.sendError(TftpErrors.IllegalTftpOp)
            raise TftpException("Received WRQ from server while in download")

        elif isinstance(pkt, TftpPacketERR):
            self.sendError(TftpErrors.IllegalTftpOp)
            log.debug("Received ERR packet: %s", pkt)
            if pkt.errorcode == TftpErrors.FileNotFound:
                raise TftpFileNotFoundError("File not found")
            else:
                raise TftpException("Received ERR from server: {}".format(pkt))

        else:
            self.sendError(TftpErrors.IllegalTftpOp)
            raise TftpException("Received unknown packet type from server: %s" % pkt)

        # By default, no state change.
        return self
213259
def serve(self):
        """"""
        while self.ready:
            try:
                self.tick()
            except (KeyboardInterrupt, SystemExit):
                raise
            except Exception:
                self.error_log(
                    'Error in HTTPServer.tick', level=logging.ERROR,
                    traceback=True,
                )

            if self.interrupt:
                while self.interrupt is True:
                    # Wait for self.stop() to complete. See _set_interrupt.
                    time.sleep(0.1)
                if self.interrupt:
                    raise self.interrupt
679976
def handle_message(self, msg):
        
        # log messages received so that no one else has to
        if self._logger.isEnabledFor(logging.DEBUG):
            self._logger.debug(
                "received from {}: {}"
                .format(self.bind_address_string, repr(str(msg))))

        if msg.mtype == Message.INFORM:
            return self.handle_inform(msg)
        elif msg.mtype == Message.REPLY:
            return self.handle_reply(msg)
        elif msg.mtype == Message.REQUEST:
            return self.handle_request(msg)
        else:
            self._logger.error("Unexpected message type from server ['%s']."
                               % (msg,))
1204896
def send_packet(self):
        """"""
        waiter, packet = self.client.waiters.popleft()
        self.logger.debug('sending packet: %s', binascii.hexlify(packet))
        self.client.active_transaction = waiter
        self.client.in_transaction = True
        self.client.active_packet = packet
        self.reset_cmd_timeout()
        self.transport.write(packet)
1121945
def _handle_lines(self):
        """"""
        while b'\xdd' in self._buffer:
            linebuf, self._buffer = self._buffer.rsplit(b'\xdd', 1)
            line = linebuf[-19:]
            self._buffer += linebuf[:-19]
            if self._valid_packet(line):
                self._handle_raw_packet(line)
            else:
                self.logger.warning('dropping invalid data: %s',
                                    binascii.hexlify(line))
45827
async def send(self, pkt):
        """"""
        if not await self.check_ping_timeout():
            return
        if self.upgrading:
            self.packet_backlog.append(pkt)
        else:
            await self.queue.put(pkt)
        self.server.logger.info('%s: Sending packet %s data %s',
                                self.sid, packet.packet_names[pkt.packet_type],
                                pkt.data if not isinstance(pkt.data, bytes)
                                else '<binary>')
164776
def handle(self):
        
        self.logger = self.server.logger

        # create a packet structure
        packet = iis()
        packet.datain = self.rfile
        packet.dataout = self.wfile

        # decode the header
        size = struct.calcsize('8h')
        line = packet.datain.read(size)
        n = len(line)
        if n < size:
            return

        while n > 0:
            try:
                bytes = struct.unpack('8h', line)
            except Exception:
                self.logger.error('error unpacking the data.')
                for exctn in sys.exc_info():
                    print(exctn)

            # TODO: verify checksum

            # decode the packet fields
            subunit = bytes[2]
            subunit077 = subunit & 0o77
            tid = bytes[0]
            x = bytes[4] & 0o177777
            y = bytes[5] & 0o177777
            z = bytes[6] & 0o177777
            t = bytes[7] & 0o17777
            ndatabytes = - bytes[1]

            # are the bytes packed?
            if (not(tid & PACKED)):
                ndatabytes *= 2

            # populate the packet structure
            packet.subunit = subunit
            packet.subunit077 = subunit077
            packet.tid = tid
            packet.x = x
            packet.y = y
            packet.z = z
            packet.t = t
            packet.nbytes = ndatabytes

            # decide what to do, depending on the
            # value of subunit
            self.logger.debug("PACKET IS %o" % packet.subunit)

            if packet.subunit077 == FEEDBACK:
                self.handle_feedback(packet)

            elif packet.subunit077 == LUT:
                self.handle_lut(packet)
                # read the next packet
                line = packet.datain.read(size)
                n = len(line)
                continue

            elif packet.subunit077 == MEMORY:
                self.handle_memory(packet)
                if self.needs_update:
                    #self.display_image()
                    pass
                # read the next packet
                line = packet.datain.read(size)
                n = len(line)
                continue

            elif packet.subunit077 == WCS:
                self.handle_wcs(packet)
                line = packet.datain.read(size)
                n = len(line)
                continue

            elif packet.subunit077 == IMCURSOR:
                self.handle_imcursor(packet)
                line = packet.datain.read(size)
                n = len(line)
                continue

            else:
                self.logger.debug('?NO OP (0%o)' % (packet.subunit077))

            if not (packet.tid & IIS_READ):
                # OK, discard the rest of the data
                nbytes = packet.nbytes
                while nbytes > 0:
                    # for (nbytes = ndatabytes;  nbytes > 0;  nbytes -= n):
                    if nbytes < SZ_FIFOBUF:
                        n = nbytes
                    else:
                        n = SZ_FIFOBUF
                    m = self.rfile.read(n)
                    if m <= 0:
                        break
                    nbytes -= n

            # read the next packet
            line = packet.datain.read(size)
            n = len(line)
            if n < size:
                return
        # <--- end of the while (n) loop
        if self.needs_update:
            self.display_image()
            self.needs_update = False
595800
def handle_packet(self, packet):
        """"""

        if not isinstance(packet, RTMPPacket):
            raise ValueError("A RTMPPacket argument is required")

        return librtmp.RTMP_ClientPacket(self.rtmp, packet.packet)
523387
def streamserver_handle(cls, socket, address):
        ''''''
        request = cls.dummy_request()
        request._sock = socket
        server = None
        cls(request, address, server)
691478
function() {
    const err = Errors.createError(
      'socket timeout',
      true,
      info,
      '08S01',
      Errors.ER_SOCKET_TIMEOUT
    );
    const packetMsgs = info.getLastPackets();
    if (packetMsgs !== '') {
      err.message = err.message + '\nlast received packets:\n' + packetMsgs;
    }
    _fatalError(err, true);
  }
30779
def handle(self, sock, read_data, path, headers):
        ""
        for i in range(self.attempts):
            try:
                server_sock = eventlet.connect(
                    tuple(random.choice(self.backends)),
                )
            except socket.error:
                eventlet.sleep(self.delay)
                continue
            # Function to help track data usage
            def send_onwards(data):
                server_sock.sendall(data)
                return len(data)
            try:
                size = send_onwards(read_data)
                size += SocketMelder(sock, server_sock).run()
            except socket.error, e:
                if e.errno != errno.EPIPE:
                    raise
408089
def _incoming(self, packet):
        
        if len(packet.data) < 1:
            logger.warning('Localization packet received with incorrect' +
                           'length (length is {})'.format(len(packet.data)))
            return

        pk_type = struct.unpack('<B', packet.data[:1])[0]
        data = packet.data[1:]

        # Decoding the known packet types
        # TODO: more generic decoding scheme?
        decoded_data = None
        if pk_type == self.RANGE_STREAM_REPORT:
            if len(data) % 5 != 0:
                logger.error('Wrong range stream report data lenght')
                return
            decoded_data = {}
            raw_data = data
            for i in range(int(len(data) / 5)):
                anchor_id, distance = struct.unpack('<Bf', raw_data[:5])
                decoded_data[anchor_id] = distance
                raw_data = raw_data[5:]

        pk = LocalizationPacket(pk_type, data, decoded_data)
        self.receivedLocationPacket.call(pk)
218182
def handle_event(self, packet):
        """"""
        if packet.get('command'):
            task = self.send_command_ack(packet['id'], packet['command'])
            self.loop.create_task(task)
1121537
private void handlePacket(Stanza packet) {
        if (packet instanceof Message) {
            Message msg = (Message) packet;
            // Check to see if the user left the queue.
            ExtensionElement pe = msg.getExtension("depart-queue", "http://jabber.org/protocol/workgroup");
            ExtensionElement queueStatus = msg.getExtension("queue-status", "http://jabber.org/protocol/workgroup");

            if (pe != null) {
                fireQueueDepartedEvent();
            }
            else if (queueStatus != null) {
                QueueUpdate queueUpdate = (QueueUpdate) queueStatus;
                if (queueUpdate.getPosition() != -1) {
                    fireQueuePositionEvent(queueUpdate.getPosition());
                }
                if (queueUpdate.getRemaingTime() != -1) {
                    fireQueueTimeEvent(queueUpdate.getRemaingTime());
                }
            }

            else {
                // Check if a room invitation was sent and if the sender is the workgroup
                MUCUser mucUser = msg.getExtension("x", "http://jabber.org/protocol/muc#user");
                MUCUser.Invite invite = mucUser != null ? mucUser.getInvite() : null;
                if (invite != null && workgroupJID.equals(invite.getFrom())) {
                    String sessionID = null;
                    Map<String, List<String>> metaData = null;

                    pe = msg.getExtension(SessionID.ELEMENT_NAME,
                            SessionID.NAMESPACE);
                    if (pe != null) {
                        sessionID = ((SessionID) pe).getSessionID();
                    }

                    pe = msg.getExtension(MetaData.ELEMENT_NAME,
                            MetaData.NAMESPACE);
                    if (pe != null) {
                        metaData = ((MetaData) pe).getMetaData();
                    }

                    WorkgroupInvitation inv = new WorkgroupInvitation(connection.getUser(), msg.getFrom(),
                            workgroupJID, sessionID, msg.getBody(),
                            msg.getFrom(), metaData);

                    fireInvitationEvent(inv);
                }
            }
        }
    }