Had to do this because sometimes packets somehow get moving by 1 byte https://github.com/pulviscriptor/agario-client/issues/46#issuecomment-169764771
432672
function(packet, err) {
        var crash = true;

        this.emitEvent('packetError', packet, err, function() {
            crash = false;
        });

        if(crash) {
            if(this.debug >= 1)
                this.log('Packet error detected! Check packetError event in README.md');
            throw err;
        }
    }
55184
def retransmit(self, data):
        

        # If that shit is still in self.event_uuids, then that means we STILL
        # haven't gotten a response from the client. Then we resend that shit
        # and WAIT
        if data["euuid"] in self.event_uuids:
            # Increment the current retry count of the euuid
            self.event_uuids[data["euuid"]] += 1

            # If we've tried more than the maximum, just log an error
            # and stahap.
            if (self.event_uuids[data["euuid"]] > self.max_retries or
                    data["cuuid"] not in self.registry):
                logger.warning("<%s> Retry limit exceeded. "
                               "Timed out waiting for client for "
                               "event: %s" % (data["cuuid"], data["euuid"]))
                logger.warning("<%s> Deleting event from currently processing "
                               "event uuids" % data["cuuid"])
                del self.event_uuids[data["euuid"]]
            else:
                # Retransmit that shit
                logger.debug("<%s> Timed out waiting for response. Retry %s. "
                             "Retransmitting message: "
                             "%s" % (data["cuuid"],
                                     pformat(self.event_uuids[data["euuid"]]),
                                     data["response"]))

                # Look up the host and port based on cuuid
                host = self.registry[data["cuuid"]]["host"]
                port = self.registry[data["cuuid"]]["port"]

                # Send the packet to the client
                self.listener.send_datagram(data["response"], (host, port))

                # Then we set another schedule to check again
                logger.debug("<%s> Scheduling to retry in %s "
                             "seconds" % (data["cuuid"], str(self.timeout)))
                self.listener.call_later(self.timeout, self.retransmit, data)
67500
function broadcast(connections, packet) {
    var i = connections.length;
    while (i--) {
        connections[i].write(packet);
        flush(connections[i]);
    }
}
222935
private void setHandshakeFailure(ChannelHandlerContext ctx, Throwable cause, boolean closeInbound,
                                     boolean notify, boolean alwaysFlushAndClose) {
        try {
            // Release all resources such as internal buffers that SSLEngine
            // is managing.
            outboundClosed = true;
            engine.closeOutbound();

            if (closeInbound) {
                try {
                    engine.closeInbound();
                } catch (SSLException e) {
                    if (logger.isDebugEnabled()) {
                        // only log in debug mode as it most likely harmless and latest chrome still trigger
                        // this all the time.
                        //
                        // See https://github.com/netty/netty/issues/1340
                        String msg = e.getMessage();
                        if (msg == null || !(msg.contains("possible truncation attack") ||
                                msg.contains("closing inbound before receiving peer's close_notify"))) {
                            logger.debug("{} SSLEngine.closeInbound() raised an exception.", ctx.channel(), e);
                        }
                    }
                }
            }
            if (handshakePromise.tryFailure(cause) || alwaysFlushAndClose) {
                SslUtils.handleHandshakeFailure(ctx, cause, notify);
            }
        } finally {
            // Ensure we remove and fail all pending writes in all cases and so release memory quickly.
            releaseAndFailAll(cause);
        }
    }
856101
public IoBuffer encodePacket(Packet packet) {
        IoBuffer out = null;
        Header header = packet.getHeader();
        int channelId = header.getChannelId();
        //log.trace("Channel id: {}", channelId);
        IRTMPEvent message = packet.getMessage();
        if (message instanceof ChunkSize) {
            ChunkSize chunkSizeMsg = (ChunkSize) message;
            ((RTMPConnection) Red5.getConnectionLocal()).getState().setWriteChunkSize(chunkSizeMsg.getSize());
        }
        // normally the message is expected not to be dropped
        if (!dropMessage(channelId, message)) {
            //log.trace("Header time: {} message timestamp: {}", header.getTimer(), message.getTimestamp());
            IoBuffer data = encodeMessage(header, message);
            if (data != null) {
                RTMP rtmp = ((RTMPConnection) Red5.getConnectionLocal()).getState();
                // set last write packet
                rtmp.setLastWritePacket(channelId, packet);
                // ensure we're at the beginning
                if (data.position() != 0) {
                    data.flip();
                } else {
                    data.rewind();
                }
                // length of the data to be chunked
                int dataLen = data.limit();
                header.setSize(dataLen);
                //if (log.isTraceEnabled()) {
                    //log.trace("Message: {}", data);
                //}
                // chunk size for writing
                int chunkSize = rtmp.getWriteChunkSize();
                // number of chunks to write
                int numChunks = (int) Math.ceil(dataLen / (float) chunkSize);
                // get last header
                Header lastHeader = rtmp.getLastWriteHeader(channelId);
                if (log.isTraceEnabled()) {
                    log.trace("Channel id: {} chunkSize: {}", channelId, chunkSize);
                }
                // attempt to properly guess the size of the buffer we'll need
                int bufSize = dataLen + 18 + (numChunks * 2);
                //log.trace("Allocated buffer size: {}", bufSize);
                out = IoBuffer.allocate(bufSize, false);
                out.setAutoExpand(true);
                do {
                    // encode the header
                    encodeHeader(header, lastHeader, out);
                    // write a chunk
                    byte[] buf = new byte[Math.min(chunkSize, data.remaining())];
                    data.get(buf);
                    //log.trace("Buffer: {}", Hex.encodeHexString(buf));
                    out.put(buf);
                    // move header over to last header
                    lastHeader = header.clone();
                } while (data.hasRemaining());
                // collapse the time stamps on the last header after decode is complete
                lastHeader.setTimerBase(lastHeader.getTimer());
                // clear the delta
                lastHeader.setTimerDelta(0);
                // set last write header
                rtmp.setLastWriteHeader(channelId, lastHeader);
                data.free();
                out.flip();
                data = null;
            }
        }
        message.release();
        return out;
    }
222974
private void flushBytes() throws IOException
	{
		if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) {  //306998.15
			logger.logp(Level.FINE, CLASS_NAME,"flushBytes", "flushBytes");
        }
		if (!committed)
		{
			if (!_hasFlushed && obs != null)
			{
				_hasFlushed = true;
				if (obsList!=null){
					for (int i=0;i<obsList.size();i++){
						obsList.get(i).alertFirstFlush();
					}
				}
				else {
				obs.alertFirstFlush();
			}
		}
		}
		committed = true;
		if (count > 0)
		{
			writeOut(buf, 0, count);
// PK34562			out.flush();
			count = 0;
		}
		// PK34562 Start
//  		else if ( count == 0 && out != null) {
//			out.flush();
//		}
		else if (count == 0)
		{
	        if(response != null && response.getFlushMode())
	        {
	        	if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) {  //PK34562
	    			logger.logp(Level.FINE, CLASS_NAME,"flushBytes", "Count 0 still flush mode is true , forceful flush");
	            }
	            response.flushBufferedContent();
	        } else if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) {  //PK34562
				logger.logp(Level.FINE, CLASS_NAME,"flushBytes", "flush mode is false");
	        }	 
		}
		// PK34562 End
	}
1151956
private void throttledTransfer(MockResponse policy, Socket socket, BufferedSource source,
      BufferedSink sink, long byteCount, boolean isRequest) throws IOException {
    if (byteCount == 0) return;

    Buffer buffer = new Buffer();
    long bytesPerPeriod = policy.getThrottleBytesPerPeriod();
    long periodDelayMs = policy.getThrottlePeriod(TimeUnit.MILLISECONDS);

    long halfByteCount = byteCount / 2;
    boolean disconnectHalfway = isRequest
        ? policy.getSocketPolicy() == DISCONNECT_DURING_REQUEST_BODY
        : policy.getSocketPolicy() == DISCONNECT_DURING_RESPONSE_BODY;

    while (!socket.isClosed()) {
      for (long b = 0; b < bytesPerPeriod; ) {
        // Ensure we do not read past the allotted bytes in this period.
        long toRead = Math.min(byteCount, bytesPerPeriod - b);
        // Ensure we do not read past halfway if the policy will kill the connection.
        if (disconnectHalfway) {
          toRead = Math.min(toRead, byteCount - halfByteCount);
        }

        long read = source.read(buffer, toRead);
        if (read == -1) return;

        sink.write(buffer, read);
        sink.flush();
        b += read;
        byteCount -= read;

        if (disconnectHalfway && byteCount == halfByteCount) {
          socket.close();
          return;
        }

        if (byteCount == 0) return;
      }

      if (periodDelayMs != 0) {
        try {
          Thread.sleep(periodDelayMs);
        } catch (InterruptedException e) {
          throw new AssertionError(e);
        }
      }
    }
  }
196179
private void readPayload() throws IOException, InterruptedException {
        if (incomingBuffer.remaining() != 0) { // have we read length bytes?
            int rc = sock.read(incomingBuffer); // sock is non-blocking, so ok
            if (rc < 0) {
                throw new EndOfStreamException(
                        "Unable to read additional data from client sessionid 0x"
                        + Long.toHexString(sessionId)
                        + ", likely client has closed socket");
            }
        }

        if (incomingBuffer.remaining() == 0) { // have we read length bytes?
            packetReceived();
            incomingBuffer.flip();
            if (!initialized) {
                readConnectRequest();
            } else {
                readRequest();
            }
            lenBuffer.clear();
            incomingBuffer = lenBuffer;
        }
    }
844586
public synchronized long write(final ByteBuffer buf) {
		if (!validState) {
			throw new InvalidStateException();
		}
		final int packet_size = (HEADER_LEN + buf.limit() + FOOTER_LEN); // short + int + data + byte
		final boolean useDirectIO = (packet_size > (1 << bits));
		try {
			if (useDirectIO) {
				log.warn("WARN: usingDirectIO packet size is greater (" + packet_size
						+ ") than file buffer (" + bufOutput.capacity() + ")");
			}
			// Align output
			if (alignBlocks && !useDirectIO) {
				final int diffOffset = nextBlockBoundary(offsetOutputUncommited);
				if (packet_size > diffOffset) {
					// log.warn("WARN: aligning offset=" + offsetOutputUncommited + " to=" +
					// (offsetOutputUncommited+diffOffset) + " needed=" + packet_size + " allowed=" +
					// diffOffset);
					alignBuffer(diffOffset);
					offsetOutputUncommited += diffOffset;
				}
			}
			// Remember current offset
			final long offset = offsetOutputUncommited;
			// Write pending buffered data to disk
			if (bufOutput.remaining() < packet_size) {
				flushBuffer();
			}
			// Write new data to buffer
			bufOutput.put((byte) ((MAGIC >> 8) & 0xFF)); 	// Header - Magic (short, 2 bytes, msb-first)
			bufOutput.put((byte) (MAGIC & 0xFF)); 		// Header - Magic (short, 2 bytes, lsb-last)
			bufOutput.putInt(buf.limit()); 				// Header - Data Size (int, 4 bytes)
			if (useDirectIO) {
				bufOutput.flip();
				fcOutput.write(new ByteBuffer[] {
						bufOutput, buf, ByteBuffer.wrap(new byte[] {
							MAGIC_FOOT
						})
				}); // Write Header + Data + Footer
				bufOutput.clear();
				offsetOutputUncommited = offsetOutputCommited = fcOutput.position();
				if (syncOnFlush) {
					fcOutput.force(false);
					if (callback != null)
						callback.synched(offsetOutputCommited);
				}
			} else {
				bufOutput.put(buf); // Data Body
				bufOutput.put(MAGIC_FOOT); // Footer
				// Increment offset of buffered data (header + user-data)
				offsetOutputUncommited += packet_size;
				if (flushOnWrite) {
					flushBuffer();
				}
			}
			//
			return offset;
		} catch (Exception e) {
			log.error("Exception in write()", e);
		}
		return -1L;
	}
1263942
static RawPacket nextPacket(final InputStream is) throws IOException {
        byte[] lengthBuffer = readLengthSeq(is);
        int length = (lengthBuffer[0] & 0xff) + ((lengthBuffer[1] & 0xff) << 8) + ((lengthBuffer[2] & 0xff) << 16);
        if (length == -1) {
            return null;
        }

        if (length < 0) {
            throw new IOException("Got negative packet size: " + length);
        }

        final int packetSeq = lengthBuffer[3];

        final byte[] rawBytes = new byte[length];

        final int nr = ReadUtil.safeRead(is, rawBytes);
        if (nr != length) {
            throw new IOException("EOF. Expected " + length + ", got " + nr);
        }

        return new RawPacket(ByteBuffer.wrap(rawBytes).order(ByteOrder.LITTLE_ENDIAN),
                             packetSeq);
    }
580881
function applySdpHack(sdp) {
    var parts = sdp.split('b=AS:30');
    if (parts.length === 2) {
        // increase max data transfer bandwidth to 100 Mbps
        return parts[0] + 'b=AS:102400' + parts[1];
    } else {
        return sdp;
    }
}
1264416
def _write_packet(self, packet, sec=None, usec=None, caplen=None, wirelen=None):
        
        if caplen is None:
            caplen = len(packet)
        if wirelen is None:
            wirelen = caplen
        if sec is None or usec is None:
            t=time.time()
            it = int(t)
            if sec is None:
                sec = it
            if usec is None:
                usec = int(round((t-it)*1000000))
        self.f.write(struct.pack(self.endian+"IIII", sec, usec, caplen, wirelen))
        self.f.write(packet)
        if self.gz and self.sync:
            self.f.flush()
549434
def write(sock, payload):
    """"""
    try:
        length = sock.send(payload)
    except ssl.SSLError as e:
        return -1, (ssl.SSLError, e.strerror if strerror else e.message)
    except socket.herror as (_, msg):
        return -1, (socket.error, msg)
    except socket.gaierror as (_, msg):
        return -1, (socket.gaierror, msg)
    except socket.timeout:
        return -1, (socket.timeout, "timeout")
    except socket.error as (_, msg):
        return -1, (socket.error, msg)
    
    return length, None
1257162
private void maybePushConfigChunk() {
        String currentChunk = responseContent.toString(CHARSET);

        int separatorIndex = currentChunk.indexOf("\n\n\n\n");
        if (separatorIndex > 0) {
            String content = currentChunk.substring(0, separatorIndex);
            streamingConfigObservable.onNext(content.trim());
            responseContent.clear();
            responseContent.writeBytes(currentChunk.substring(separatorIndex + 4).getBytes(CHARSET));
        }
    }
187971
private void append2slowUUID() {
    final int CHUNK_SZ = 1 << H2O.LOG_CHK;
    if( _sparseLen > CHUNK_SZ )
      throw new ArrayIndexOutOfBoundsException(_sparseLen);
    if( _ds==null && _ls!=null ) { // This can happen for columns with all NAs and then a UUID
      _xs=null;
      alloc_doubles(_sparseLen);
      Arrays.fill(_ls,C16Chunk._LO_NA);
      Arrays.fill(_ds,Double.longBitsToDouble(C16Chunk._HI_NA));
    }
    if( _ls != null && _ls.length > 0 ) {
      _ls = MemoryManager.arrayCopyOf(_ls,_sparseLen<<1);
      _ds = MemoryManager.arrayCopyOf(_ds,_sparseLen<<1);
    } else {
      alloc_mantissa(4);
      alloc_doubles(4);
    }
    assert _sparseLen == 0 || _ls.length > _sparseLen:"_ls.length = " + _ls.length + ", _sparseLen = " + _sparseLen;
  }
783045
void gatherProtocol(int maxPos) throws IOException {
        // protocol buffer has max capacity, shouldn't need resizing
        try {
            while(this.bufferPosition < maxPos) {
                byte b = this.buffer[this.bufferPosition];
                this.bufferPosition++;

                if (gotCR) {
                    if (b == NatsConnection.LF) {
                        this.protocolBuffer.flip();
                        this.mode = Mode.PARSE_PROTO;
                        this.gotCR = false;
                        break;
                    } else {
                        throw new IllegalStateException("Bad socket data, no LF after CR");
                    }
                } else if (b == NatsConnection.CR) {
                    this.gotCR = true;
                } else {
                    if (!protocolBuffer.hasRemaining()) {
                        this.protocolBuffer = this.connection.enlargeBuffer(this.protocolBuffer, 0); // just double it
                    }
                    this.protocolBuffer.put(b);
                }
            }
        } catch (IllegalStateException | NumberFormatException | NullPointerException ex) {
            this.encounteredProtocolError(ex);
        }
    }
99604
function _get_binary_packet()
    {
        if (!is_resource($this->fsock) || feof($this->fsock)) {
            user_error('Connection closed prematurely');
            $this->bitmap = 0;
            return false;
        }

        $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838
        $raw = fread($this->fsock, $this->decrypt_block_size);

        if (!strlen($raw)) {
            return '';
        }

        if ($this->decrypt !== false) {
            $raw = $this->decrypt->decrypt($raw);
        }
        if ($raw === false) {
            user_error('Unable to decrypt content');
            return false;
        }

        if (strlen($raw) < 5) {
            return false;
        }
        extract(unpack('Npacket_length/Cpadding_length', $this->_string_shift($raw, 5)));

        $remaining_length = $packet_length + 4 - $this->decrypt_block_size;

        // quoting <http://tools.ietf.org/html/rfc4253#section-6.1>,
        // "implementations SHOULD check that the packet length is reasonable"
        // PuTTY uses 0x9000 as the actual max packet size and so to shall we
        if ($remaining_length < -$this->decrypt_block_size || $remaining_length > 0x9000 || $remaining_length % $this->decrypt_block_size != 0) {
            user_error('Invalid size');
            return false;
        }

        $buffer = '';
        while ($remaining_length > 0) {
            $temp = fread($this->fsock, $remaining_length);
            if ($temp === false || feof($this->fsock)) {
                user_error('Error reading from socket');
                $this->bitmap = 0;
                return false;
            }
            $buffer.= $temp;
            $remaining_length-= strlen($temp);
        }
        $stop = strtok(microtime(), ' ') + strtok('');
        if (strlen($buffer)) {
            $raw.= $this->decrypt !== false ? $this->decrypt->decrypt($buffer) : $buffer;
        }

        $payload = $this->_string_shift($raw, $packet_length - $padding_length - 1);
        $padding = $this->_string_shift($raw, $padding_length); // should leave $raw empty

        if ($this->hmac_check !== false) {
            $hmac = fread($this->fsock, $this->hmac_size);
            if ($hmac === false || strlen($hmac) != $this->hmac_size) {
                user_error('Error reading socket');
                $this->bitmap = 0;
                return false;
            } elseif ($hmac != $this->hmac_check->hash(pack('NNCa*', $this->get_seq_no, $packet_length, $padding_length, $payload . $padding))) {
                user_error('Invalid HMAC');
                return false;
            }
        }

        //if ($this->decompress) {
        //    $payload = gzinflate(substr($payload, 2));
        //}

        $this->get_seq_no++;

        if (defined('NET_SSH2_LOGGING')) {
            $current = strtok(microtime(), ' ') + strtok('');
            $message_number = isset($this->message_numbers[ord($payload[0])]) ? $this->message_numbers[ord($payload[0])] : 'UNKNOWN (' . ord($payload[0]) . ')';
            $message_number = '<- ' . $message_number .
                              ' (since last: ' . round($current - $this->last_packet, 4) . ', network: ' . round($stop - $start, 4) . 's)';
            $this->_append_log($message_number, $payload);
            $this->last_packet = $current;
        }

        return $this->_filter($payload);
    }