i am trying to make my small websocket php class in which i wanted to make functions like onopen onmessage etc like node js [i know there are other libraries out there but i wanted to learn it myself].so far i am able to successfully recieve message from js websocket to php with this code below
<?php
$host = "localhost";
$port = 8001;
$sockets=array();
function sendAll($connections,$msg){
foreach ($connections as $each) {
send($each,$msg);
}
}
function send($client,$msg){
$msg = chr(129) . chr(strlen($msg)) . $msg;
socket_write($client,$msg,strlen($msg));
}
function handshake($client){
$request = socket_read($client, 5000);
preg_match('#Sec-WebSocket-Key: (.*)
#', $request, $matches);
$key = base64_encode(pack(
'H*',
sha1($matches[1] . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')
));
$headers = "HTTP/1.1 101 Switching Protocols
";
$headers .= "Upgrade: websocket
";
$headers .= "Connection: Upgrade
";
$headers .= "Sec-WebSocket-Version: 13
";
$headers .= "Sec-WebSocket-Accept: $key
";
socket_write($client, $headers, strlen($headers));
}
// Create WebSocket.
$server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($server, SOL_SOCKET, SO_REUSEADDR, 1);
socket_set_nonblock($server);
socket_bind($server, $host, $port);
socket_listen($server);
while(true){
$client = socket_accept($server);
if($client != false){
usleep(100);
handshake($client);
array_push($sockets,$client);
print_r($sockets);
}
else{
if(count($sockets) > 0){
foreach ($sockets as $each) {
$msg = socket_read($each,5000);
if($msg != false){
filter($msg);
// send($each,"testing");
}
}
}
}
}
function filter($msg){
$msg = unpack("c*",$msg);
foreach ($msg as $value) {
echo chr($value);
}
// print_r($msg);
}
?>
after some research i found that websocket sends message in binary. i cant convert that message into plain text. i dont know which language or format that data is sent into.tell me please which format is it and how to read it as plain text sample picture below
question from:
https://stackoverflow.com/questions/65644666/how-to-get-socket-read-value-to-plain-text-sent-from-javascript-in-php-websocket 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…