public function setReceiveEvent($conn)
{
$bytes = '';
$headerLength = 4;
$dataLength = -1;
$id = null;
$conn->on('receive', function ($conn, $chunk) use(&$bytes, &$headerLength, &$dataLength, &$id) {
$bytes .= $chunk;
while (true) {
$length = strlen($bytes);
if ($dataLength < 0 && $length >= $headerLength) {
list(, $dataLength) = unpack('N', substr($bytes, 0, 4));
if (($dataLength & 0x80000000) !== 0) {
$dataLength &= 0x7fffffff;
$headerLength = 8;
}
}
if ($headerLength === 8 && $id === null && $length >= $headerLength) {
list(, $id) = unpack('N', substr($bytes, 4, 4));
}
if ($dataLength >= 0 && $length - $headerLength >= $dataLength) {
$onreceive = $conn->onreceive;
$onreceive($conn, substr($bytes, $headerLength, $dataLength), $id);
$bytes = substr($bytes, $headerLength + $dataLength);
$id = null;
$headerLength = 4;
$dataLength = -1;
} else {
break;
}
}
});
}