PHP Websocket Server hybi10

后端 未结 2 2012
庸人自扰
庸人自扰 2020-12-16 04:53

So Chrome 14 has implemented hybi10 version of websockets. I have a in house program that our company uses via chrome that uses websockets which is broken with this change.<

相关标签:
2条回答
  • 2020-12-16 05:15

    i just completed a class wich makes the PHP-Websocket-Server of Nico Kaiser (https://github.com/nicokaiser/php-websocket) capable of handling hybi-10 frames and handshake. You can download the new class here: http://lemmingzshadow.net/386/php-websocket-serverclient-nach-draft-hybi-10/ (Connection.php)

    0 讨论(0)
  • 2020-12-16 05:29

    This code assumes no errors or malformed frames and is based on this answer - How to (de)construct data frames in WebSockets hybi 08+?.

    This code is very basic and is far from a complete solution. It works for my purposes (which are pretty basic). Hopefully it is of use to others.

    function handle_data($data){
        $bytes = $data;
        $data_length = "";
        $mask = "";
        $coded_data = "" ;
        $decoded_data = "";        
        $data_length = $bytes[1] & 127;
        if($data_length === 126){
           $mask = substr($bytes, 4, 8);
           $coded_data = substr($bytes, 8);
        }else if($data_length === 127){
            $mask = substr($bytes, 10, 14);
            $coded_data = substr($bytes, 14);
        }else{
            $mask = substr($bytes, 2, 6);
            $coded_data = substr($bytes, 6);
        }
        for($i=0;$i<strlen($coded_data);$i++){
            $decoded_data .= $coded_data[$i] ^ $mask[$i%4];
        }
        $this->log("Server Received->".$decoded_data);
        return true;
    }
    

    Here is the code to send data back. Again this is pretty basic, it assumes you are sending a single text frame. No continuation frames etc. No error checking either. Hopefully others find it useful.

    public function send($data)
    {
        $frame = Array();
        $encoded = "";
        $frame[0] = 0x81;
        $data_length = strlen($data);
    
        if($data_length <= 125){
            $frame[1] = $data_length;    
        }else{
            $frame[1] = 126;  
            $frame[2] = $data_length >> 8;
            $frame[3] = $data_length & 0xFF; 
        }
    
        for($i=0;$i<sizeof($frame);$i++){
            $encoded .= chr($frame[$i]);
        }
    
        $encoded .= $data;
        write_to_socket($this->socket, $encoded);  
        return true;     
    }
    
    0 讨论(0)
提交回复
热议问题