Problem with PHP and Html5 Sockets

Asked

Viewed 138 times

0

I have a problem, I have a page called server.php and another client.php, the client code is as follows:

<script src="scripts/jQuery/jquery-3.2.1.min.js"></script>
<script>
     
var socket = new WebSocket('ws://127.0.0.1:4000');

 socket.onopen = function () {
         
}
 socket.onmessage  = function(){
         alert("Chegou mensagem");
}

And the.php server is

<?php 
    
    ob_implicit_flush();
	set_time_limit(0);

    $host = "127.0.0.1";
	$porta = 4000;
 
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
	socket_bind($socket, $host, $porta);
	socket_listen($socket);

	echo "Esperando conexão com a porta: ".$porta;
	$con = false;

	switch(socket_select($r=array($socket),$w=array($socket),$e=array($socket),30)){
		   case 0:
		        echo "Tempo de espera terminou";
		   break;
		   case 1:
		        echo "Conectado na porta: ".$porta;
				$con = socket_accept($socket);
		   break;
		   case 2:
		        echo "Não foi possível se conectar!";
		   break;
	}
	
			 
	socket_recv($con,$resposta,1024,MSG_WAITALL);
	 if(preg_match("/Sec-WebSocket-Key:(.*)\==/i", $resposta, $rep)){
          $key = $rep[1]."==";
	 }
	$chave = base64_encode(sha1($key."258EAFA5-E914-47DA-95CA-C5AB0DC85B11"));

          $upgrade  = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n".
          "Upgrade: websocket\r\n".
          "Connection: Upgrade\r\n".
          "WebSocket-Origin: $host\r\n".
          "WebSocket-Location: ws://$host:$porta/\r\n".
          "Sec-WebSocket-Accept:$chave\r\n\r\n";

		  if(socket_write($socket, $upgrade, strlen($upgrade))){
			  echo "Protocolo foi enviado";
		  }else{
			  echo socket_strerror(socket_last_error());
		  }	

	
?>

The problem is that the socket_write() function does not send the socket to the client, the message should not appear on the client page "Message arrived"?

  • Welcome to Stackoverflow, Edgar! Enjoy your visit and do the tour to learn more about how the site works! :)

  • Thanks! , could help me with this problem?

1 answer

0


After you have made Handshake, you can send the messages, need to mask before sending is receive.

//Desmascara a mensagem recebida
function unmask($text) {
    $length = ord($text[1]) & 127;
    if($length == 126) {
        $masks = substr($text, 4, 4);
        $data = substr($text, 8);
    }
    elseif($length == 127) {
        $masks = substr($text, 10, 4);
        $data = substr($text, 14);
    }
    else {
        $masks = substr($text, 2, 4);
        $data = substr($text, 6);
    }
    $text = "";
    for ($i = 0; $i < strlen($data); ++$i) {
        $text .= $data[$i] ^ $masks[$i%4];
    }
    return $text;
}

//Mascara a mensagem para enviar para o cliente.
function mask($text)
{
    $b1 = 0x80 | (0x1 & 0x0f);
    $length = strlen($text);

    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.$text;
}

Receive the frame and unmask the message:

socket_recv($con,$resposta,1024,MSG_WAITALL);
$msg = unmask($resposta);

Send the message:

$msg = "Teste";
$frame = mask(msg);
socket_write($socket, $frame, strlen($frame));

I advise you to use a library this one for example Ratchet.

  • Thank you for your reply, but should I follow exactly this instruction to mask a message? I mean, I can’t customize or it’s a socket pattern anyway?

  • Keeps giving this error "failed: Websocket Opening Handshake timed out" in the client console

  • Websocket is not a "browser socket", Websocket is a protocol, to communicate client/server you need to follow protocol specifications.

  • The error was because the client protocol version is different from the server.

  • And how can I solve?

  • Use a library that already exists or create yourself.

  • If you are creating here you have the link to the specification in English.

  • Okay thanks, I’ll use Ratchet like you advised me.

  • @Edgar Marks the answer as the right one

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.