--- RECEIVE PACKET ---
507931
public synchronized boolean receive(Tree message) {

		// Update timestamp
		if (timeoutMillis > 0) {
			timeoutAt = System.currentTimeMillis() + timeoutMillis;
		}

		// Check sequence number
		long seq = message.get("seq", -1);
		if (seq > -1) {
			if (seq - 1 == prevSeq) {
				prevSeq = seq;
			} else {

				// Process later
				pool.put(seq, message);
				return false;
			}
		} else {
			prevSeq = -1;
		}

		// Process current message
		boolean close = processMessage(message);

		// Process pooled messages
		long nextSeq = prevSeq;
		while (true) {
			Tree nextMessage = pool.remove(++nextSeq);
			if (nextMessage == null) {
				break;
			}
			prevSeq = nextSeq;
			if (processMessage(nextMessage)) {
				close = true;
			}
		}

		// True = remove stream from registry
		return close;
	}
1213199
def on_packet_received(self, pkt):
        
        if not pkt:
            return
        if self.store:
            self.lst.append(pkt)
        if self.prn:
            result = self.prn(pkt)
            if result is not None:
                print(result)
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)
779678
public static IoBuffer encodeOutgoingData(Packet packet) {
        log.debug("encode outgoing: {}", packet);
        // get the payload data
        IoBuffer data = packet.getData();
        // get the frame length based on the byte count
        int frameLen = data.limit();
        // start with frame length + 2b (header info)
        IoBuffer buffer = IoBuffer.allocate(frameLen + 2, false);
        buffer.setAutoExpand(true);
        // set the proper flags / opcode for the data
        byte frameInfo = (byte) (1 << 7);
        switch (packet.getType()) {
            case TEXT:
                if (log.isTraceEnabled()) {
                    log.trace("Encoding text frame  \r\n{}", new String(packet.getData().array()));
                }
                frameInfo = (byte) (frameInfo | 1);
                break;
            case BINARY:
                log.trace("Encoding binary frame");
                frameInfo = (byte) (frameInfo | 2);
                break;
            case CLOSE:
                frameInfo = (byte) (frameInfo | 8);
                break;
            case CONTINUATION:
                frameInfo = (byte) (frameInfo | 0);
                break;
            case PING:
                log.trace("ping out");
                frameInfo = (byte) (frameInfo | 9);
                break;
            case PONG:
                log.trace("pong out");
                frameInfo = (byte) (frameInfo | 0xa);
                break;
            default:
                break;
        }
        buffer.put(frameInfo);
        // set the frame length
        log.trace("Frame length {} ", frameLen);
        if (frameLen <= 125) {
            buffer.put((byte) ((byte) frameLen & (byte) 0x7F));
        } else if (frameLen > 125 && frameLen <= 65535) {
            buffer.put((byte) ((byte) 126 & (byte) 0x7F));
            buffer.putShort((short) frameLen);
        } else {
            buffer.put((byte) ((byte) 127 & (byte) 0x7F));
            buffer.putLong((int) frameLen);
        }
        buffer.put(data);
        buffer.flip();
        if (log.isTraceEnabled()) {
            log.trace("Encoded: {}", buffer);
        }
        return buffer;
    }
1169321
def recv(self, stream, crc_mode=1, retry=16, timeout=60, delay=1, quiet=0):
        '''
        
        '''

        # initiate protocol
        error_count = 0
        char = 0
        cancel = 0
        while True:
            # first try CRC mode, if this fails,
            # fall back to checksum mode
            if error_count >= retry:
                self.abort(timeout=timeout)
                return None
            elif crc_mode and error_count < (retry / 2):
                if not self.putc(CRC):
                    time.sleep(delay)
                    error_count += 1
            else:
                crc_mode = 0
                if not self.putc(NAK):
                    time.sleep(delay)
                    error_count += 1

            char = self.getc(1, timeout)
            if not char:
                error_count += 1
                continue
            elif char == SOH:
                #crc_mode = 0
                break
            elif char == STX:
                break
            elif char == CAN:
                if cancel:
                    return None
                else:
                    cancel = 1
            else:
                error_count += 1

        # read data
        error_count = 0
        income_size = 0
        packet_size = 128
        sequence = 1
        cancel = 0
        while True:
            while True:
                if char == SOH:
                    packet_size = 128
                    break
                elif char == STX:
                    packet_size = 1024
                    break
                elif char == EOT:
                    # We received an EOT, so send an ACK and return the received
                    # data length
                    self.putc(ACK)
                    return income_size
                elif char == CAN:
                    # cancel at two consecutive cancels
                    if cancel:
                        return None
                    else:
                        cancel = 1
                else:
                    if not quiet:
                        print >> sys.stderr, \
                            'recv ERROR expected SOH/EOT, got', ord(char)
                    error_count += 1
                    if error_count >= retry:
                        self.abort()
                        return None
            # read sequence
            error_count = 0
            cancel = 0
            seq1 = ord(self.getc(1))
            seq2 = 0xff - ord(self.getc(1))
            if seq1 == sequence and seq2 == sequence:
                # sequence is ok, read packet
                # packet_size + checksum
                data = self.getc(packet_size + 1 + crc_mode, timeout)
                if crc_mode:
                    csum = (ord(data[-2]) << 8) + ord(data[-1])
                    data = data[:-2]
                    log.debug('CRC (%04x <> %04x)' % \
                        (csum, self.calc_crc(data)))
                    valid = csum == self.calc_crc(data)
                else:
                    csum = data[-1]
                    data = data[:-1]
                    log.debug('checksum (checksum(%02x <> %02x)' % \
                        (ord(csum), self.calc_checksum(data)))
                    valid = ord(csum) == self.calc_checksum(data)

                # valid data, append chunk
                if valid:
                    income_size += len(data)
                    stream.write(data)
                    self.putc(ACK)
                    sequence = (sequence + 1) % 0x100
                    char = self.getc(1, timeout)
                    continue
            else:
                # consume data
                self.getc(packet_size + 1 + crc_mode)
                self.debug('expecting sequence %d, got %d/%d' % \
                    (sequence, seq1, seq2))

            # something went wrong, request retransmission
            self.putc(NAK)
1256760
@Override
    public ByteBuffer read(ByteBuffer receiveBuffer) throws IOException {
        if (!doHandshake(receiveBuffer))
            return null;

        if (!initialHSComplete)
            throw new IllegalStateException("The initial handshake is not complete.");

        if (log.isDebugEnabled()) {
            log.debug("session {} read data status -> {}, initialHSComplete -> {}", session.getSessionId(),
                    session.isOpen(), initialHSComplete);
        }

        merge(receiveBuffer);
        if (!receivedPacketBuf.hasRemaining()) {
            return null;
        }

        needIO:
        while (true) {
            SSLEngineResult result = unwrap();

            if (log.isDebugEnabled()) {
                log.debug("Session {} read data result -> {}, receivedPacketBuf -> {}, appBufSize -> {}",
                        session.getSessionId(), result.toString().replace('\n', ' '),
                        receivedPacketBuf.remaining(), receivedAppBuf.remaining());
            }

            switch (result.getStatus()) {
                case BUFFER_OVERFLOW: {
                    resizeAppBuffer();
                    // retry the operation.
                }
                break;
                case BUFFER_UNDERFLOW: {
                    int packetBufferSize = sslEngine.getSession().getPacketBufferSize();
                    if (receivedPacketBuf.remaining() >= packetBufferSize) {
                        break; // retry the operation.
                    } else {
                        break needIO;
                    }
                }
                case OK: {
                    if (result.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_TASK) {
                        doTasks();
                    }
                    if (receivedPacketBuf.hasRemaining()) {
                        break; // retry the operation.
                    } else {
                        break needIO;
                    }
                }

                case CLOSED: {
                    log.info("Session {} read data failure. SSLEngine will close inbound", session.getSessionId());
                    closeInbound();
                }
                break needIO;

                default:
                    throw new SecureNetException(StringUtils.replace("Session {} SSLEngine read data exception. status -> {}",
                            session.getSessionId(), result.getStatus()));
            }
        }

        return getReceivedAppBuf();
    }
1056284
function Packet(length) {
    this._index = 0;
    if (length instanceof Buffer) {
        this.buf = length;
    } else {
        this.buf = Buffer.alloc(length, 0);

        this.writeInt32LE(length);
    }
}
1228552
@Override
	public void send( AbstractPacket packet ) throws PacketTransportException
    {
        if (closed)
   			throw new PacketTransportException("Transport is closed");
        
        sender.send(packet);
    }
1229282
private void readHeaderFromBuffer(final ByteBuffer buffer) {
    int toRead = MIN_RECV_PACKET - headerOffset;
    int available = buffer.remaining();
    toRead = Math.min(toRead, available);
    getLogger().debug("Reading %d header bytes", toRead);
    buffer.get(header, headerOffset, toRead);
    headerOffset += toRead;
  }
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()
240986
private void receiveMessage(ClientSocket client, DataInputStream buffer, byte from, StateConnection expected)
            throws IOException
    {
        if (ServerImpl.checkValidity(client, from, expected))
        {
            final byte dest = buffer.readByte();
            final byte type = buffer.readByte();
            final int size = buffer.readInt();
            if (size > 0)
            {
                final byte[] clientData = new byte[size];
                if (buffer.read(clientData) != -1) // CHECKSTYLE IGNORE LINE: TrailingComment|NestedIfDepth
                {
                    final DataInputStream clientBuffer = new DataInputStream(new ByteArrayInputStream(clientData));
                    decodeMessage(type, from, dest, clientBuffer);
                }
            }
            final int headerSize = 4;
            bandwidth += headerSize + size;
        }
    }
441165
def receive_packet(self, time=0):
        
        if time == 0:
            try:
                return self.in_queue.get(False)
            except queue.Empty:
                return None
        elif time < 0:
            try:
                return self.in_queue.get(True)
            except queue.Empty:
                return None
        else:
            try:
                return self.in_queue.get(True, time)
            except queue.Empty:
                return None
256651
def read_packet(self, size=MTU):
        
        while True:
            try:
                blocktype, blocklen = struct.unpack(self.endian + "2I",
                                                    self.f.read(8))
            except struct.error:
                return None
            block = self.f.read(blocklen - 12)
            if blocklen % 4:
                pad = self.f.read(4 - (blocklen % 4))
                warning("PcapNg: bad blocklen %d (MUST be a multiple of 4. "
                        "Ignored padding %r" % (blocklen, pad))
            try:
                if (blocklen,) != struct.unpack(self.endian + 'I',
                                                self.f.read(4)):
                    warning("PcapNg: Invalid pcapng block (bad blocklen)")
            except struct.error:
                return None
            res = self.blocktypes.get(blocktype,
                                      lambda block, size: None)(block, size)
            if res is not None:
                return res
81639
protected void processReceivedMessage(DatagramPacket packet, byte[] buffer) {

		String received = new String(buffer).trim();
		String tokens[] = received.split("\\|");
		if (tokens.length != 3) {
			logger.warn("Malformed UDP message received (" + received + ")!");
			return;
		}

		// Check prefix and nodeID
		if (!namespace.equals(tokens[0]) || nodeID.equals(tokens[1])) {
			return;
		}
		if (tokens[1].isEmpty()) {
			logger.warn("Empty nodeID received!");
			return;
		}

		// Get source hostname or IP
		String host;
		try {
			InetAddress address = packet.getAddress();
			if (useHostname) {
				host = address.getHostName();
				if (host == null || host.isEmpty() || host.contains("localhost")) {
					host = address.getHostAddress();
				}
			} else {
				host = address.getHostAddress();
				if (host == null || host.isEmpty() || host.startsWith("127.")) {
					host = address.getHostName();
				}
			}
			if (host == null || host.isEmpty()) {
				logger.warn("Unable to detect sender's hostname!");
				return;
			}
		} catch (Exception cause) {
			logger.warn("Unable to detect sender's IP address or hostname!", cause);
			return;
		}
		int port = 0;
		try {
			port = Integer.parseInt(tokens[2]);
			if (port < 1) {
				logger.warn("Invalid port number (" + port + ")!");
				return;
			}
		} catch (Exception cause) {
			logger.warn("Invalid port number format (" + tokens[2] + ")!");
			return;
		}

		// Notify TCP Transporter
		transporter.udpPacketReceived(tokens[1], host.toLowerCase(), port);
	}
223230
private int readPacket(byte[] packet, int offset, int psize) throws IOException {
        int length = 0;
        if(position+psize<source.length)
    	{
    		length=psize;
    		System.arraycopy(source, position, packet, offset, length);
    		position+=psize;
    	}
    	else if(position<source.length)
    	{
    		length=source.length-position;
    		System.arraycopy(source, position, packet, offset, length);
    		position+=length;
    	}
        
        return length;
    }
507761
def send_by_packet(self, data):
        
        total_sent = 0
        while total_sent < PACKET_SIZE:
            sent = self.sock.send(data[total_sent:])
            if sent == 0:
                raise RuntimeError("socket connection broken")
            total_sent += sent
        return total_sent
1298389
public void send(String nodeID, byte[] packet) {
		if (nodeID == null) {
			logger.warn("Unable to send (missing nodeID)!");
			return;
		}
		if (packet == null || packet.length < 6) {
			logger.warn("Cannot send empty packet to node " + nodeID + "!");
			return;
		}
		SendBuffer buffer = null;
		try {

			// Get or create buffer
			boolean newBuffer = false;
			synchronized (buffers) {
				buffer = buffers.get(nodeID);
				if (buffer == null) {

					// Create new connection
					RemoteAddress address = transporter.getAddress(nodeID);
					if (address == null) {
						logger.warn("Unknown node ID (" + nodeID + ")!");
						return;
					}
					buffer = new SendBuffer(nodeID, address.host, address.port, debug);
					append(nodeID, buffer, packet);
					buffers.put(nodeID, buffer);
					newBuffer = true;
				} else {

					// Try to append to buffer
					if (!buffer.append(packet)) {

						// Buffer is closed
						RemoteAddress address = transporter.getAddress(nodeID);
						buffer = new SendBuffer(nodeID, address.host, address.port, debug);
						append(nodeID, buffer, packet);
						buffers.put(nodeID, buffer);
						newBuffer = true;
					}
				}
			}
			if (newBuffer) {

				// Close older connections
				if (maxConnections > 0) {
					cleanup();
				}

				// Add to opened buffers
				opened.add(buffer);

			} else if (buffer.key != null) {

				// Mark as writable
				buffer.key.interestOps(SelectionKey.OP_WRITE);
			}

			// Wake up selector
			if (selector != null) {
				selector.wakeup();
			}

		} catch (Throwable cause) {
			synchronized (buffers) {
				buffers.remove(nodeID);
			}
			LinkedList<byte[]> packets;
			if (buffer != null) {
				packets = buffer.getUnsentPackets();
			} else {
				packets = new LinkedList<>();
			}
			if (packets.isEmpty() && packet != null) {
				packets.addLast(packet);
			}
			transporter.unableToSend(nodeID, packets, cause);
		}
	}