Handle the incoming message.

@param packet
incoming message packet
762266
public void handleMessageReceived(Packet packet) {
        if (log.isTraceEnabled()) {
            log.trace("handleMessageReceived - {}", sessionId);
        }
        // set the packet expiration time if maxHandlingTimeout is not disabled (set to 0)
        if (maxHandlingTimeout > 0) {
            packet.setExpirationTime(System.currentTimeMillis() + maxHandlingTimeout);
        }
        if (executor != null) {
            final byte dataType = packet.getHeader().getDataType();
            // route these types outside the executor
            switch (dataType) {
                case Constants.TYPE_PING:
                case Constants.TYPE_ABORT:
                case Constants.TYPE_BYTES_READ:
                case Constants.TYPE_CHUNK_SIZE:
                case Constants.TYPE_CLIENT_BANDWIDTH:
                case Constants.TYPE_SERVER_BANDWIDTH:
                    // pass message to the handler
                    try {
                        handler.messageReceived(this, packet);
                    } catch (Exception e) {
                        log.error("Error processing received message {}", sessionId, e);
                    }
                    break;
                default:
                    final String messageType = getMessageType(packet);
                    try {
                        // increment the packet number
                        final long packetNumber = packetSequence.incrementAndGet();
                        if (executorQueueSizeToDropAudioPackets > 0 && currentQueueSize.get() >= executorQueueSizeToDropAudioPackets) {
                            if (packet.getHeader().getDataType() == Constants.TYPE_AUDIO_DATA) {
                                // if there's a backlog of messages in the queue. Flash might have sent a burst of messages after a network congestion. Throw away packets that we are able to discard.
                                log.info("Queue threshold reached. Discarding packet: session=[{}], msgType=[{}], packetNum=[{}]", sessionId, messageType, packetNumber);
                                return;
                            }
                        }
                        int streamId = packet.getHeader().getStreamId().intValue();
                        if (log.isTraceEnabled()) {
                            log.trace("Handling message for streamId: {}, channelId: {} Channels: {}", streamId, packet.getHeader().getChannelId(), channels);
                        }
                        // create a task to setProcessing the message
                        ReceivedMessageTask task = new ReceivedMessageTask(sessionId, packet, handler, this);
                        task.setPacketNumber(packetNumber);
                        // create a task queue
                        ReceivedMessageTaskQueue newStreamTasks = new ReceivedMessageTaskQueue(streamId, this);
                        // put the queue in the task by stream map
                        ReceivedMessageTaskQueue currentStreamTasks = tasksByStreams.putIfAbsent(streamId, newStreamTasks);
                        if (currentStreamTasks != null) {
                            // add the task to the existing queue
                            currentStreamTasks.addTask(task);
                        } else {
                            // add the task to the newly created and just added queue
                            newStreamTasks.addTask(task);
                        }
                    } catch (Exception e) {
                        log.error("Incoming message handling failed on session=[" + sessionId + "], messageType=[" + messageType + "]", e);
                        if (log.isDebugEnabled()) {
                            log.debug("Execution rejected on {} - {}", sessionId, RTMP.states[getStateCode()]);
                            log.debug("Lock permits - decode: {} encode: {}", decoderLock.availablePermits(), encoderLock.availablePermits());
                        }
                    }
            }
        } else {
            log.debug("Executor is null on {} state: {}", sessionId, RTMP.states[getStateCode()]);
            // pass message to the handler
            try {
                handler.messageReceived(this, packet);
            } catch (Exception e) {
                log.error("Error processing received message {} state: {}", sessionId, RTMP.states[getStateCode()], e);
            }
        }
    }
1353768
public void handle(Throwable t) {
    System.out.flush();
    System.err.println(t.getClass().getSimpleName() + ":" + t.getMessage());
    if (debug)
      t.printStackTrace();
  }
372755
private void handleIncomingResponseMessage(SerialMessage incomingMessage) {
		logger.debug("Message type = RESPONSE");
		switch (incomingMessage.getMessageClass()) {
			case GetVersion:
				handleGetVersionResponse(incomingMessage);
				if (incomingMessage.getMessageClass() == this.lastSentMessage.getExpectedReply() && !incomingMessage.isTransActionCanceled()) {
					notifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));
					transactionCompleted.release();
					logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits());
				}
				break;
			case MemoryGetId:
				handleMemoryGetId(incomingMessage);
				if (incomingMessage.getMessageClass() == this.lastSentMessage.getExpectedReply() && !incomingMessage.isTransActionCanceled()) {
					notifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));
					transactionCompleted.release();
					logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits());
				}
				break;
			case SerialApiGetInitData:
				handleSerialApiGetInitDataResponse(incomingMessage);
				if (incomingMessage.getMessageClass() == this.lastSentMessage.getExpectedReply() && !incomingMessage.isTransActionCanceled()) {
					notifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));
					transactionCompleted.release();
					logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits());
				}
				break;
			case IdentifyNode:
				handleIdentifyNodeResponse(incomingMessage);
				if (incomingMessage.getMessageClass() == this.lastSentMessage.getExpectedReply() && !incomingMessage.isTransActionCanceled()) {
					notifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));
					transactionCompleted.release();
					logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits());
				}
				break;
			case RequestNodeInfo:
				handleRequestNodeInfoResponse(incomingMessage);
				break;
			case SerialApiGetCapabilities:
				handleSerialAPIGetCapabilitiesResponse(incomingMessage);
				if (incomingMessage.getMessageClass() == this.lastSentMessage.getExpectedReply() && !incomingMessage.isTransActionCanceled()) {
					notifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));
					transactionCompleted.release();
					logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits());
				}
				break;
			case SendData:
				handleSendDataResponse(incomingMessage);
				break;
			default:
				logger.warn(String.format("TODO: Implement processing of Response Message = %s (0x%02X)",
						incomingMessage.getMessageClass().getLabel(),
						incomingMessage.getMessageClass().getKey()));
				break;				
		}
	}
571665
public static void queuePacket(Packet packet){
        if(isEnabled){
            if(LOGGER.isDebugEnabled()){
                LOGGER.debug("queue packet latency = " + (System.currentTimeMillis() - packet.getCreateTime()));
            }
        }
    }
103362
public void handleData(String data) {
		if (data == null) return;
		text = data;
		sendEvent(new TextInputEvent(this.user, getPayload(), data));
		if (handler != null)
			handler.onType(data);
	}
1207967
private void handleChannelCallback(final String message) {
		// Channel callback
		updateConnectionHeartbeat();

		// JSON callback
		final JSONArray jsonArray = new JSONArray(new JSONTokener(message));

		if(connectionFeatureManager.isConnectionFeatureActive(BitfinexConnectionFeature.SEQ_ALL)) {
			sequenceNumberAuditor.auditPackage(jsonArray);
		}

		final int channel = jsonArray.getInt(0);
		final ChannelCallbackHandler channelCallbackHandler = channelIdToHandlerMap.get(channel);
		if (channelCallbackHandler == null) {
			logger.error("Unable to determine symbol for channel {} / data is {} ", channel, jsonArray);
			reconnect();
			return;
		}
		String action = null;
		final JSONArray payload;
		if (jsonArray.get(1) instanceof String) {
			action = jsonArray.getString(1);
			payload = jsonArray.optJSONArray(2);
		} else {
			payload = jsonArray.optJSONArray(1);
		}
		if (Objects.equals(action, "hb")) {
			quoteManager.updateChannelHeartbeat(channelCallbackHandler.getSymbol());
		}
		try {
			if (payload == null) {
				return;
			}
			channelCallbackHandler.handleChannelData(action, payload);
		} catch (final BitfinexClientException e) {
			logger.error("Got exception while handling callback", e);
		}
	}
134048
def handle(self, pkt, raddress, rport):
        ""
        if isinstance(pkt, TftpPacketACK):
            log.debug("Received ACK for packet %d" % pkt.blocknumber)
            # Is this an ack to the one we just sent?
            if self.context.next_block == pkt.blocknumber:
                if self.context.pending_complete:
                    log.info("Received ACK to final DAT, we're done.")
                    return None
                else:
                    log.debug("Good ACK, sending next DAT")
                    self.context.next_block += 1
                    log.debug("Incremented next_block to %d",
                        self.context.next_block)
                    self.context.pending_complete = self.sendDAT()

            elif pkt.blocknumber < self.context.next_block:
                log.warning("Received duplicate ACK for block %d"
                    % pkt.blocknumber)
                self.context.metrics.add_dup(pkt)

            else:
                log.warning("Oooh, time warp. Received ACK to packet we "
                         "didn't send yet. Discarding.")
                self.context.metrics.errors += 1
            return self
        elif isinstance(pkt, TftpPacketERR):
            log.error("Received ERR packet from peer: %s" % str(pkt))
            raise TftpException("Received ERR packet from peer: %s" % str(pkt))
        else:
            log.warning("Discarding unsupported packet: %s" % str(pkt))
            return self
212267
function onmessage(packet) {
    if (arguments.length === 2) packet = arguments[1];
    packet = parse(packet);

    if (allowed(packet)) emit(packet);
  }
114242
public function onPingRequestPacket(PingRequestPacket $packet)
    {
        //a ping data contains a long, but because the client just expects the same data back no point in parsing/reencoding it
        $ping = new PingResponsePacket();
        $ping->setPingData($packet->getPingData());

        //disconnect the client with the ping response
        $this->disconnectClient($ping);
    }
237559
def incoming(self, packet):
        
        # This might be done prettier ;-)
        console_text = packet.data.decode('UTF-8')

        self.receivedChar.call(console_text)
161640
protected void processSynAckPacket(Packet packet) {
        String serverIp = packet.getSrcIpAddr();
        int serverPort = packet.getSrcPort();
        String clientIp = packet.getDestIpAddr();
        int clientPort = packet.getDestPort();
        String clientId = makeClientId(clientIp, clientPort);
        TcpServerScript serverFragmentWriter = scriptFragments.get(clientId);
        if ( serverFragmentWriter == null ) {
            serverFragmentWriter = new TcpServerScript(emitterFactory.getRptScriptEmitter(OUTPUT_TYPE,
                    "tcp-server-"
                            + serverIp + "-" + serverPort + "-client-" + clientIp + "-" + clientPort + "-ServerSide"));
        }
        else if ( serverFragmentWriter.getState() != ScriptState.CLOSED ) {
            throw new RptScriptsCreatorFailureException(
                    "Attempting to open already opened tcp connection from server composer:" + clientId);
        }
        serverFragmentWriter.writeAccept(serverIp, serverPort, packet);
        scriptFragments.put(clientId, serverFragmentWriter);
    }
695306
private void handlePeerMessage(PeerMessage message) {
		// Ignore our own updates
		Peer peer = PeerUtils.fromMessage(message, Status.ACTIVE);
		if(peer.getId().equals(self)) {
			return;
		}

		// Add or update the peer
		synchronized(this) {
			if(!peers.containsKey(peer.getId())) {
				add(peer);
			}
			else {
				update(peer);
			}
		}
	}
1290852
protected void writingMessage(Packet message) {
        if (message.getMessage() instanceof VideoData) {
            Number streamId = message.getHeader().getStreamId();
            final AtomicInteger value = new AtomicInteger();
            AtomicInteger old = pendingVideos.putIfAbsent(streamId.doubleValue(), value);
            if (old == null) {
                old = value;
            }
            old.incrementAndGet();
        }
    }
545838
void handleCommunicationIssue(Exception io) {
        // If we are connecting or disconnecting, note exception and leave
        statusLock.lock();
        try {
            if (this.connecting || this.disconnecting || this.status == Status.CLOSED || this.isDraining()) {
                this.exceptionDuringConnectChange = io;
                return;
            }
        } finally {
            statusLock.unlock();
        }

        processException(io);

        // Spawn a thread so we don't have timing issues with
        // waiting on read/write threads
        executor.submit(() -> {
            try {
                this.closeSocket(true);
            } catch (InterruptedException e) {
                processException(e);
            }
        });
    }
431846
private void handleEvent(PrimitiveEvent event) {
    log.trace("Received {}", event);
    Set<Consumer<PrimitiveEvent>> listeners = eventListeners.get(event.type());
    if (listeners != null) {
      listeners.forEach(l -> l.accept(event));
    }
  }
735957
def handle_packet(queue, packet, header)
      begin
        # Continue to dispatch/ack requests even when terminating otherwise will block results
        # Ideally would reject requests when terminating but broker client does not yet support that
        case packet
        when Push, Request then dispatch_request(packet, queue)
        when Result        then deliver_response(packet)
        end
        @sender.message_received
      rescue Exception => e
        ErrorTracker.log(self, "#{queue} queue processing error", e)
      ensure
        # Relying on fact that all dispatches/deliveries are synchronous and therefore
        # need to have completed or failed by now, thus allowing packet acknowledgement
        header.ack
      end
      true
    end
1257106
public void received(byte packetID, byte[] packet) {
		executor.execute(() -> {

			// Parse message
			Tree data;
			try {
				data = serializer.read(packet);
			} catch (Exception cause) {
				logger.warn("Unable to parse incoming message!", cause);
				return;
			}

			// Send message to proper component
			try {

				switch (packetID) {
				case PACKET_EVENT_ID:

					// Incoming event
					if (debug) {
						logger.info("Event message received:\r\n" + data);
					}
					eventbus.receiveEvent(data);
					return;

				case PACKET_REQUEST_ID:

					// Incoming request
					if (debug) {
						logger.info("Request message received:\r\n" + data);
					}
					registry.receiveRequest(data);
					return;

				case PACKET_RESPONSE_ID:

					// Incoming response
					if (debug) {
						logger.info("Response message received:\r\n" + data);
					}
					registry.receiveResponse(data);
					return;

				case PACKET_PING_ID:

					// Send pong
					if (debug) {
						logger.info("Ping message received:\r\n" + data);
					}
					String sender = data.get("sender", "");
					if (sender == null || sender.isEmpty()) {
						logger.warn("Missing \"sender\" property:\r\n" + data);
						return;
					}
					data.put("sender", this.nodeID);
					data.put("arrived", System.currentTimeMillis());
					writer.send(sender, serialize(PACKET_PONG_ID, data));
					return;

				case PACKET_PONG_ID:

					// Pong received
					if (debug) {
						logger.info("Pong message received:\r\n" + data);
					}
					registry.receivePong(data);
					return;

				case PACKET_GOSSIP_REQ_ID:

					// Incoming gossip request
					processGossipRequest(data);
					return;

				case PACKET_GOSSIP_RSP_ID:

					// Incoming gossip request
					processGossipResponse(data);
					return;

				case PACKET_GOSSIP_HELLO_ID:

					// Incoming "hello" message
					processGossipHello(data);
					return;

				default:
					logger.warn("Unsupported message ID (" + packetID + ")!");
				}

			} catch (Exception cause) {
				logger.warn("Unable to process incoming message!", cause);
			}
		});
	}