is there a valid packet (from another thread) for this app/instance?
963363
def check_packet(self):
        ''''''
        if not os.path.exists(self.packet_file()):
            # No packet file, we're good
            return True
        else:
            # There's already a file, but is it still running?
            try:
                with open(self.packet_file()) as f:
                    packet = json.loads(f.read())
                if time.time() - packet['last_time'] > 3.0*packet['poll_time']:
                    # We haven't heard a ping in too long. It's probably dead
                    return True
                else:
                    # Still getting pings.. probably still a live process
                    return False
            except:
                # Failed to read file... try again in a second
                time.sleep(random.random()*2)
                return self.check_packet()
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);

    }
387048
def write_packets(self):
        """"""
        while self.running:
            if len(self.write_queue) > 0:
                self.write_queue[0].send(self.client)
                self.write_queue.pop(0)
344886
def _sense_packet_to_data(packet):
        """"""
        data = bytearray(0)
        last = 0
        i = 1
        while (i < len(packet)):
            if not (last == 2 and packet[i] == 0):
                data.append(packet[i])
            last = packet[i]
            i += 1

        return data
952869
async def _receive_packet(self, pkt):
        """"""
        packet_name = packet.packet_names[pkt.packet_type] \
            if pkt.packet_type < len(packet.packet_names) else 'UNKNOWN'
        self.logger.info(
            'Received packet %s data %s', packet_name,
            pkt.data if not isinstance(pkt.data, bytes) else '<binary>')
        if pkt.packet_type == packet.MESSAGE:
            await self._trigger_event('message', pkt.data, run_async=True)
        elif pkt.packet_type == packet.PONG:
            self.pong_received = True
        elif pkt.packet_type == packet.NOOP:
            pass
        else:
            self.logger.error('Received unexpected packet of type %s',
                              pkt.packet_type)
1204708
def _packet_loop(self):
        
        while self._is_running:
            # Only wait if there are no more packets in the inbox
            if self.inbox.empty() \
                    and not self.new_packet.wait(self._packet_timeout):
                continue
            ip, port, packet = self.inbox.get()
            if self.inbox.empty():
                self.new_packet.clear()
            self.debug(u"{}".format(packet))

            if packet.header.message_type == MsgType.CONFIG:
                self._do_config_packet(packet, ip, port)
            elif packet.header.message_type == MsgType.UPDATE:
                self._do_update_packet(packet)
941737
def stream_to_packet(data):
    
    if len(data) < 6:
        return None

    # unpack the length
    pktlen = struct.unpack(">H", data[4:6])[0] + 6
    if (len(data) < pktlen):
        return None

    return (data[:pktlen], data[pktlen:])
170348
@Override
	public boolean handleIncomingData()
	{
		lastRecvActivity = System.currentTimeMillis();
		
		while (inputBuffer.remaining() > 0)
		{		
			if (packetInputBuffer.size() == 0)
			{
				if (inputBuffer.remaining() >= 4) // packet_size = sizeof(int) = 4
				{
					int packetSize = inputBuffer.getInt();
					
					// Security check
					int actualMaxPacketSize = Integer.MAX_VALUE;
					if (maxPacketSize != -1)
						actualMaxPacketSize = trustedConnection ? maxPacketSize : 1024;
					
					if (packetSize > actualMaxPacketSize)
					{
						log.error("#"+id+" packet is too large : "+packetSize+" (maxPacketSize="+actualMaxPacketSize+"), dropping client.");
						return false;
					}
					
					packetInputBuffer.setSize(packetSize);
				}
				else
					return true; // Not enough data to proceed ...
			}
			else
			{
				// Append to current packet
				int readAmount = Math.min(inputBuffer.remaining(), packetInputBuffer.size() - currentInputOffset);
				packetInputBuffer.getFrom(inputBuffer, currentInputOffset, readAmount);
				currentInputOffset += readAmount;
				
				// Packet is complete ?
				if (currentInputOffset == packetInputBuffer.size())
				{
					AbstractPacket packet = unserializePacket(packetInputBuffer);
					if (packet == null)
						return false; // Invalid packet
					packetInputBuffer.clear();
					currentInputOffset = 0;
					
					if (traceEnabled)
	                    log.trace("#"+id+" Received "+packet);
					
					if (listener != null)
						trustedConnection = listener.packetReceived(packet);
				}
			}
		}
		
		return true;
	}
744533
async def _handle_data(self, data):
        
        try:
            _, _, verification_tag, chunks = parse_packet(data)
        except ValueError:
            return

        # is this an init?
        init_chunk = len([x for x in chunks if isinstance(x, InitChunk)])
        if init_chunk:
            assert len(chunks) == 1
            expected_tag = 0
        else:
            expected_tag = self._local_verification_tag

        # verify tag
        if verification_tag != expected_tag:
            self.__log_debug('Bad verification tag %d vs %d',
                             verification_tag, expected_tag)
            return

        # handle chunks
        for chunk in chunks:
            await self._receive_chunk(chunk)

        # send SACK if needed
        if self._sack_needed:
            await self._send_sack()
841200
void messageReceived(MessagePacket packet) {
        if (!getCluster().isMaster())
            return;
        LOG.debug("Received packet {}", packet);

        final long now = System.nanoTime();
        packet.setTimestamp(now);

        final short node = packet.getNode();
        final NodePeer peer = peers.get(node);
        if (peer == null)
            throw new RuntimeException("Message received from unhandled node " + node);

        try {
            peer.receivePacket(packet); // we're now running in the executor we installed in the netty pipeline.
        } catch (InterruptedException ex) {
            LOG.error("InterruptedException", ex);
            throw new RuntimeException(ex);
        }
    }
1193844
def packet_write(self):
        """"""
        bytes_written = 0
        
        if self.sock == NC.INVALID_SOCKET:
            return NC.ERR_NO_CONN, bytes_written
        
        while len(self.out_packet) > 0:
            pkt = self.out_packet[0]
            write_length, status = nyamuk_net.write(self.sock, pkt.payload)
            if write_length > 0:
                pkt.to_process -= write_length
                pkt.pos += write_length
                
                bytes_written += write_length
                
                if pkt.to_process > 0:
                    return NC.ERR_SUCCESS, bytes_written
            else:
                if status == errno.EAGAIN or status == errno.EWOULDBLOCK:
                    return NC.ERR_SUCCESS, bytes_written
                elif status == errno.ECONNRESET:
                    return NC.ERR_CONN_LOST, bytes_written
                else:
                    return NC.ERR_UNKNOWN, bytes_written
            
            """
            if pkt.command & 0xF6 == NC.CMD_PUBLISH and self.on_publish is not None:
                self.in_callback = True
                self.on_publish(pkt.mid)
                self.in_callback = False
            """
            
            #next
            del self.out_packet[0]
            
            #free data (unnecessary)
            
            self.last_msg_out = time.time()
            
        
        return NC.ERR_SUCCESS, bytes_written
846488
def _on_open(self, _):
        """"""
        nick = self._format_nick(self._nick, self._pwd)
        data = {"cmd": "join", "channel": self._channel, "nick": nick}
        self._send_packet(data)
        self._thread = True
        threading.Thread(target=self._ping).start()
1056284
function Packet(length) {
    this._index = 0;
    if (length instanceof Buffer) {
        this.buf = length;
    } else {
        this.buf = Buffer.alloc(length, 0);

        this.writeInt32LE(length);
    }
}
46131
def validate_packet(packet):
    
    if not isinstance(packet, bytes):
        raise UnpackException('invalid packet')

    packet_length = len(packet)

    if packet_length < 8 or packet_length > 2**16:
        raise UnpackException('invalid packet')

    if packet_length != int.from_bytes(packet[2:4], byteorder='big'):
        raise UnpackException('invalid packet')

    version = packet[0]
    if version == 0 or version >= 128:
        raise UnpackException('invalid packet')
221074
public void send(Packet packet) {
        if (log.isTraceEnabled()) {
            log.trace("send packet: {}", packet);
        }
        // no handshake flag, queue the packet
        if (session.containsAttribute(Constants.HANDSHAKE_COMPLETE)) {
            try {
                // clear any queued items first
                queue.forEach(entry -> {
                    session.write(entry);
                    queue.remove(entry);
                });
            } catch (Exception e) {
                log.warn("Exception draining queued packets on session: {}", session.getId(), e);
            }
            // process the incoming packet
            session.write(packet);
        } else {
            if (handshakeWriteFuture != null) {
                log.warn("Handshake is not complete yet on session: {} written? {}", session.getId(), handshakeWriteFuture.isWritten(), handshakeWriteFuture.getException());
            } else {
                log.warn("Handshake is not complete yet on session: {}", session.getId());
            }
            // not queuing pings
            MessageType type = packet.getType();
            if (type != MessageType.PING && type != MessageType.PONG) {
                log.info("Placing {} message in session: {} queue", type, session.getId());
                queue.offer(packet);
            }
        }
    }
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);
    }
892581
def _get_packet(self, socket):
        
        data, (ip, port) = socket.recvfrom(self._buffer_size)
        packet, remainder = self._unpack(data)
        self.inbox.put((ip, port, packet))
        self.new_packet.set()
        self.debug(u"RX: {}".format(packet))

        if packet.header.sequence_number is not None:
            # Packet needs to be acknowledged
            self._send_ack(ip, port, packet)
        ack_seq = packet.header.ack_sequence_number
        if ack_seq is not None:
            # Packet got acknowledged
            with self._seq_ack_lock:
                if ack_seq in self._seq_ack:
                    self.debug(u"Seq {} got acked".format(ack_seq))
                    self._seq_ack.remove(ack_seq)
        return packet