'Convert a binary data received from stream_socket_recvfrom to string
Trying to convert binary data over websocket back to the string:
An example of code:
public function start() {
while (true) {
$newSocketArray = $this->clientSocketArray;
stream_select($newSocketArray, $null, $null, 0, 10);
if (in_array($this->socket, $newSocketArray)) {
$newSocket = stream_socket_accept($this->socket);
$this->clientSocketArray[] = $newSocket;
$this->handshake(fread($newSocket, 1024), $newSocket);
echo PHP_EOL . 'New Connection Accepted...' . stream_socket_get_name($newSocket, true);
$newSocketIndex = array_search($this->socket, $newSocketArray);
unset($newSocketArray[$newSocketIndex]);
}
sleep(1);
$data = json_decode(file_get_contents('https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD'));
$msg = json_encode(['time' => time(), 'data' => $data]);
$this->send($msg);
foreach ($newSocketArray as $newSocketArrayResource) {
$in = '';
for(;;) {
$buf = stream_socket_recvfrom($newSocketArrayResource, 1024);
if ($buf==="" || $buf === false){
break;
}
$in.=$buf;
if (!empty($in) && stream_socket_get_name($newSocketArrayResource, true)) {
echo PHP_EOL . 'Regular: ' . $in;
echo PHP_EOL . 'Unseal: ' . $this->unseal($in);
}
}
}
}
fclose($this->server);
}
public function unseal($socketData) {
$length = ord($socketData[1]) & 127;
if($length == 126) {
$masks = substr($socketData, 4, 4);
$data = substr($socketData, 8);
}
elseif($length == 127) {
$masks = substr($socketData, 10, 4);
$data = substr($socketData, 14);
}
else {
$masks = substr($socketData, 2, 4);
$data = substr($socketData, 6);
}
$socketData = "";
for ($i = 0; $i < strlen($data); ++$i) {
$socketData .= $data[$i] ^ $masks[$i%4];
}
return $socketData;
}
public function seal($socketData) {
$b1 = 0x80 | (0x1 & 0x0f);
$length = strlen($socketData);
if($length <= 125)
$header = pack('CC', $b1, $length);
elseif($length > 125 && $length < 65536)
$header = pack('CCn', $b1, 126, $length);
elseif($length >= 65536)
$header = pack('CCNN', $b1, 127, $length);
return $header.$socketData;
}
Thanks.
Updated – hanshenrik
Results:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|




