PacketListener Implementation.
199219
private void handlePacket(Stanza packet) {
        if (packet instanceof Presence) {
            Presence presence = (Presence) packet;

            // The workgroup can send us a number of different presence packets. We
            // check for different packet extensions to see what type of presence
            // packet it is.

            Resourcepart queueName = presence.getFrom().getResourceOrNull();
            WorkgroupQueue queue = queues.get(queueName);
            // If there isn't already an entry for the queue, create a new one.
            if (queue == null) {
                queue = new WorkgroupQueue(queueName);
                queues.put(queueName, queue);
            }

            // QueueOverview packet extensions contain basic information about a queue.
            QueueOverview queueOverview = presence.getExtension(QueueOverview.ELEMENT_NAME, QueueOverview.NAMESPACE);
            if (queueOverview != null) {
                if (queueOverview.getStatus() == null) {
                    queue.setStatus(WorkgroupQueue.Status.CLOSED);
                }
                else {
                    queue.setStatus(queueOverview.getStatus());
                }
                queue.setAverageWaitTime(queueOverview.getAverageWaitTime());
                queue.setOldestEntry(queueOverview.getOldestEntry());
                // Fire event.
                fireQueueUsersEvent(queue, queueOverview.getStatus(),
                        queueOverview.getAverageWaitTime(), queueOverview.getOldestEntry(),
                        null);
                return;
            }

            // QueueDetails packet extensions contain information about the users in
            // a queue.
            QueueDetails queueDetails = packet.getExtension(QueueDetails.ELEMENT_NAME, QueueDetails.NAMESPACE);
            if (queueDetails != null) {
                queue.setUsers(queueDetails.getUsers());
                // Fire event.
                fireQueueUsersEvent(queue, null, -1, null, queueDetails.getUsers());
                return;
            }

            // Notify agent packets gives an overview of agent activity in a queue.
            StandardExtensionElement notifyAgents = presence.getExtension("notify-agents", "http://jabber.org/protocol/workgroup");
            if (notifyAgents != null) {
                int currentChats = Integer.parseInt(notifyAgents.getFirstElement("current-chats", "http://jabber.org/protocol/workgroup").getText());
                int maxChats = Integer.parseInt(notifyAgents.getFirstElement("max-chats", "http://jabber.org/protocol/workgroup").getText());
                queue.setCurrentChats(currentChats);
                queue.setMaxChats(maxChats);
                // Fire event.
                // TODO: might need another event for current chats and max chats of queue
                return;
            }
        }
        else if (packet instanceof Message) {
            Message message = (Message) packet;

            // Check if a room invitation was sent and if the sender is the workgroup
            MUCUser mucUser = message.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;

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

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

                this.fireInvitationEvent(message.getFrom(), sessionID, message.getBody(),
                        message.getFrom(), metaData);
            }
        }
    }
435703
void notifyListenersNetworkReachable() {
        // NOTE: synchronized(listener) causes deadlock with listeners and Replicator.lock.
        final Set<NetworkReachabilityListener> copy = new HashSet<>(listeners);
        for (NetworkReachabilityListener listener : copy) {
            if (listener != null) { listener.networkReachable(); }
        }
    }
571665
public static void queuePacket(Packet packet){
        if(isEnabled){
            if(LOGGER.isDebugEnabled()){
                LOGGER.debug("queue packet latency = " + (System.currentTimeMillis() - packet.getCreateTime()));
            }
        }
    }
73795
def main(uport):
    """"""
    # NOTE: structure of the UDP packet is different than that of information
    #       sent via HTTP
    json_body = {
        "tags": {
            "host": "server01",
            "region": "us-west"
        },
        "time": "2009-11-10T23:00:00Z",
        "points": [{
            "measurement": "cpu_load_short",
            "fields": {
                "value": 0.64
            }
        },
            {
                "measurement": "cpu_load_short",
                "fields": {
                    "value": 0.67
                }
        }]
    }

    # make `use_udp` True and  add `udp_port` number from `influxdb.conf` file
    # no need to mention the database name since it is already configured
    client = InfluxDBClient(use_udp=True, udp_port=uport)

    # Instead of `write_points` use `send_packet`
    client.send_packet(json_body)
1338736
def raw_callback(self, raw_packet):
        """"""
        if not ';PONG;' in raw_packet:
            log.info('forwarding packet %s to clients', raw_packet)
        else:
            log.debug('forwarding packet %s to clients', raw_packet)
        writers = [i[1] for i in list(clients)]
        for writer in writers:
            writer.write(str(raw_packet).encode() + CRLF)
745568
@Override
	public void send(AbstractPacket packet) throws PacketTransportException
	{
		if (closed)
			throw new PacketTransportException("Transport is closed");
	
		if (packet.isResponseExpected())
			lastSendActivity = System.currentTimeMillis();
		
		boolean wakeUpRequired;
		synchronized (sendQueue)
		{
			wakeUpRequired = sendQueue.isEmpty();
			sendQueue.add(packet);
		}
		
		if (wakeUpRequired)
			multiplexer.wakeUp();
	}
1218586
private static Runnable asRunnable(final ClientTransport.PingCallback callback,
                                     final long roundTripTimeNanos) {
    return new Runnable() {
      @Override
      public void run() {
        callback.onSuccess(roundTripTimeNanos);
      }
    };

  }
430309
private void notifyListenersAfterResponse(ModbusResponse res) {
        synchronized (listeners) {
            for (AbstractSerialTransportListener listener : listeners) {
                listener.afterResponseRead(commPort, res);
            }
        }
    }
233274
@Override
	public boolean packetReceived(AbstractPacket packet)
    {
        AbstractQueryPacket query = (AbstractQueryPacket)packet;
    	AbstractResponsePacket response = null;
    	
    	// Process packet
        try
        {
            try
            {
                response = process(query);
            }
            catch (JMSException e)
            {
            	log.debug("#"+id+" process() failed with "+e.toString());
                response = new ErrorResponse(e);
            }
        }
        catch (Exception e)
        {
            log.error("#"+id+" Cannot process command",e);
        }
        
        // Send response
        if (response != null && query.isResponseExpected())
        {        	
            // Map endpoint id on response
            response.setEndpointId(query.getEndpointId());
            
	        try
	        {   
	            if (traceEnabled)
	                log.trace("#"+id+" Sending "+response);
	            transport.send(response);
	        }
	        catch (Exception e)
	        {
	            log.warn("#"+id+" Cannot send response to client : "+e.toString());
	            transport.close();
	        }
        }
        
        return localConnection != null; // Connection still valid ?
    }
1255369
private void finishPacket(Packet p) {

        if (p.watcherRegistration != null) {
            if(ErrorCode.OK.equals(p.respHeader.getErr())){
                this.watcherManager.register(p.watcherRegistration);
            }
        }

        synchronized (p) {
            p.finished = true;
            PacketLatency.finishPacket(p);
            if (p.cb == null && p.future == null) {
                p.notifyAll();
            }
        }

        eventThread.queuePacket(p);

    }
424757
private void initJingleSessionRequestListeners() {
        StanzaFilter initRequestFilter = new StanzaFilter() {
            // Return true if we accept this packet
            @Override
            public boolean accept(Stanza pin) {
                if (pin instanceof IQ) {
                    IQ iq = (IQ) pin;
                    if (iq.getType().equals(IQ.Type.set)) {
                        if (iq instanceof Jingle) {
                            Jingle jin = (Jingle) pin;
                            if (jin.getAction().equals(JingleActionEnum.SESSION_INITIATE)) {
                                return true;
                            }
                        }
                    }
                }
                return false;
            }
        };

        jingleSessionRequestListeners = new ArrayList<>();

        // Start a packet listener for session initiation requests
        connection.addAsyncStanzaListener(new StanzaListener() {
            @Override
            public void processStanza(Stanza packet) {
                triggerSessionRequested((Jingle) packet);
            }
        }, initRequestFilter);
    }
1062080
def read_packet(self, timeout=3.0):
        """"""

        try:
            return self.queue.get(timeout=timeout)
        except Empty:
            raise InternalTimeoutError("Timeout waiting for packet in AsyncPacketBuffer")
655199
public synchronized boolean onPacket(PacketListener listener) {
		if (listener == null) {
			return false;
		}
		if (listeners == null) {
			listeners = new PacketListener[] { listener };
		} else {
			for (PacketListener test : listeners) {
				if (test == listener) {
					return false;
				}
			}
			PacketListener[] copy = new PacketListener[listeners.length];
			System.arraycopy(listeners, 0, copy, 0, listeners.length);
			copy[listeners.length] = listener;
			listeners = copy;
		}
		try {
			if (cause == null) {
				for (byte[] bytes : buffer) {
					if (bytes == CLOSE_MARKER) {
						listener.onPacket(null, null, true);
					} else {
						listener.onPacket(bytes, null, false);
					}
				}
			} else {
				listener.onPacket(null, cause, true);
			}
		} catch (MoleculerError moleculerError) {
			throw moleculerError;
		} catch (Throwable error) {
			throw new MoleculerClientError("Unable to send packet to stream listener!", error, nodeID, null);
		}
		return true;
	}
1145358
async def receive(self, pkt):
        """"""
        self.server.logger.info('%s: Received packet %s data %s',
                                self.sid, packet.packet_names[pkt.packet_type],
                                pkt.data if not isinstance(pkt.data, bytes)
                                else '<binary>')
        if pkt.packet_type == packet.PING:
            self.last_ping = time.time()
            await self.send(packet.Packet(packet.PONG, pkt.data))
        elif pkt.packet_type == packet.MESSAGE:
            await self.server._trigger_event(
                'message', self.sid, pkt.data,
                run_async=self.server.async_handlers)
        elif pkt.packet_type == packet.UPGRADE:
            await self.send(packet.Packet(packet.NOOP))
        elif pkt.packet_type == packet.CLOSE:
            await self.close(wait=False, abort=True)
        else:
            raise exceptions.UnknownPacketError()
537144
def read_packets(self):
        """"""
        while self.running:
            packet_length = self.client.recv(2)
            if len(packet_length) < 2:
                self.stop()
                continue
            packet_length = struct.unpack("<h", packet_length)[0] - 2

            data = self.client.recv(packet_length)
            packno = data[0]

            try:
                parser = "Packet" + format(packno, 'x').upper() + "Parser"
                packet_class = getattr(packets, parser)
                packet_class().parse(self.world, self.player, data, self._evman)
            except AttributeError as e:
                pass

            if packno == 2:
                self.stop()
                continue
257906
private void send(ByteBuffer data) {
    try {
      this.socket.send(new DatagramPacket(
              data.array(),
              data.capacity(),
              this.address));
    } catch (IOException ioe) {
      logger.info("Error sending datagram packet to tracker at {}: {}.", this.address, ioe.getMessage());
    }
  }
84761
private void receiveConnected(ClientSocket client, byte from, StateConnection expected) throws IOException
    {
        if (ServerImpl.checkValidity(client, from, expected))
        {
            // Terminate last connection step and accept it
            Verbose.info(SERVER, client.getName(), " connected");
            for (final ClientListener listener : listeners)
            {
                listener.notifyClientConnected(Byte.valueOf(client.getId()), client.getName());
            }

            // Notify other clients
            for (final ClientSocket other : clients.values())
            {
                if (other.getId() == from)
                {
                    continue;
                }
                other.getOut().writeByte(NetworkMessageSystemId.OTHER_CLIENT_CONNECTED);
                ServerImpl.writeIdAndName(other, client.getId(), client.getName());
                // Send
                other.getOut().flush();
            }
        }
    }