使用php将数据推送到websocket服务器



我正在尝试将一些数据推送到websocket服务器。握手工作得很好,但当我发送数据时,服务器只是忽略它。

我读到数据应该由"x00"one_answers"xFF"字符包装,但我不知道它是否正确。(试过没有它,但仍然不工作)

push代码:

$host = '127.0.0.1';  //where is the websocket server
$port = 10000;
$origin = "http://localhost/";  //url where this script run
$data = 'server side client message';  //data to be send
$head = "GET / HTTP/1.1rn".
        "Upgrade: websocketrn".
        "Connection: Upgradern".
        "Host: $host:$portrn".
        "Origin: $originrn".
        "Sec-WebSocket-Key: k2towQT28s50DtKptTjZbg==rn".
        "Sec-WebSocket-Version: 13rnrn";
if($sock = fsockopen($host, $port, $errno, $errstr)){
    fwrite($sock, $head);
    $headers = fread($sock, 2000);
    echo nl2br($headers).'<br/><br/>';
    echo 'handshake finished<br/>'; //<--- working fine until this point
    echo '<br/>sending data: '.$data.'<br/>';
    fwrite($sock, "x00".$data."xff" ) or die('error:'.$errno.':'.$errstr); //Server ignores this message
    //$wsdata = fread($sock, 2000); 
    //echo '<br/>response: '.trim($wsdata, "x00xff").'<br/>';
    echo 'closing...';
    fclose($sock);
}else{
    echo 'fsockopen failed';
}

我错过了什么?提前感谢

My fix

<?PHP
$host = '127.0.0.1';  //where is the websocket server
$port = 10000;
$origin = "http://".$host."";  //url where this script run

// Generate the WebSocket key.
$key = generateKey();
//echo 'key: '.$key.'<br>';
$user_name='SERVER';
$user_message=$_GET['msg'];//'server side client message';
$user_color="000000";
$data =json_encode(array('type'=>'usermsg', 'name'=>$user_name, 'message'=>$user_message, 'color'=>$user_color));
$data =hybi10Encode($data);
$head = "GET / HTTP/1.1rn".
        "Upgrade: websocketrn".
        "Connection: Upgradern".
        "Host: $host:$portrn".
        "Origin: $originrn".
        "Sec-WebSocket-Key: $keyrn".
        "Sec-WebSocket-Version: 13rnrn";
if($sock = fsockopen($host, $port, $errno, $errstr)){
    fwrite($sock, $head);
    $header = fread($sock, 2000);
    //echo nl2br($header).'<br/><br/>';
    //echo 'handshake finished<br/>'; 
    $headers = array();
    $lines = preg_split("/rn/", $header);
    //echo '<br>'.$lines[5].'<br>';
    foreach($lines as $line)
    {
        $line = chop($line);
        if(preg_match('/A(S+):(.*)z/', $line, $matches))
        {
            $headers[$matches[1]] = $matches[2];
        }
    }

    if($headers['Sec-WebSocket-Accept']===false){
    //if (!preg_match('#Sec-WebSocket-Accept:s(.*)$#mUi', $headers, $matches)) {
        echo "Connection failed: Server sent invalid upgrade response:n" . $headers.'<br>';
    }else{
        //$keyAccept = trim($headers['Sec-WebSocket-Accept']);
        $keyAccept = $headers['Sec-WebSocket-Accept'];
        //echo 'keyAccept: '.$keyAccept.'<br>';
        //echo "Connection succefull: Server sent valid upgrade response:n" . $keyAccept.'<br>';;
        $expectedResonse = base64_encode(pack('H*', sha1($key . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
        //echo "Connection succefull: Server sent valid upgrade response:n" . $keyAccept.'<br>';;
        if ($keyAccept !== $expectedResonse) {
            //echo 'Server sent bad upgrade response.'.'<br>';
            //echo "ExpectedResonse $expectedResonse".'<br>';
            //echo "keyAccept ". $keyAccept.'<br>';
            echo 0;
        }else{
            echo 1;
            //echo 'Server sent correct upgrade response.'.'<br>';
            //echo '<br/>sending data: '.$data.'<br/>';
            fwrite($sock, $data ) or die('error:'.$errno.':'.$errstr); //Server ignores this message
            $wsdata = fread($sock, 2000);
            //var_dump(hybi10Decode($wsdata));
        }   
    }
    //echo 'closing...';
    fclose($sock);
}else{
    echo 'fsockopen failed';
}

/**
   * Generate a random string for WebSocket key.
   * @return string Random string
   */
 function generateKey() {
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"$&/()=[]{}0123456789';
    $key = '';
    $chars_length = strlen($chars);
    for ($i = 0; $i < 16; $i++) $key .= $chars[mt_rand(0, $chars_length-1)];
    return base64_encode($key);
  }

function hybi10Decode($data)
{
    $bytes = $data;
    $dataLength = '';
    $mask = '';
    $coded_data = '';
    $decodedData = '';
    $secondByte = sprintf('%08b', ord($bytes[1]));
    $masked = ($secondByte[0] == '1') ? true : false;
    $dataLength = ($masked === true) ? ord($bytes[1]) & 127 : ord($bytes[1]);
    if($masked === true)
    {
        if($dataLength === 126)
        {
           $mask = substr($bytes, 4, 4);
           $coded_data = substr($bytes, 8);
        }
        elseif($dataLength === 127)
        {
            $mask = substr($bytes, 10, 4);
            $coded_data = substr($bytes, 14);
        }
        else
        {
            $mask = substr($bytes, 2, 4);       
            $coded_data = substr($bytes, 6);        
        }   
        for($i = 0; $i < strlen($coded_data); $i++)
        {       
            $decodedData .= $coded_data[$i] ^ $mask[$i % 4];
        }
    }
    else
    {
        if($dataLength === 126)
        {          
           $decodedData = substr($bytes, 4);
        }
        elseif($dataLength === 127)
        {           
            $decodedData = substr($bytes, 10);
        }
        else
        {               
            $decodedData = substr($bytes, 2);       
        }       
    }   
    return $decodedData;
}

function hybi10Encode($payload, $type = 'text', $masked = true) {
    $frameHead = array();
    $frame = '';
    $payloadLength = strlen($payload);
    switch ($type) {
        case 'text':
            // first byte indicates FIN, Text-Frame (10000001):
            $frameHead[0] = 129;
            break;
        case 'close':
            // first byte indicates FIN, Close Frame(10001000):
            $frameHead[0] = 136;
            break;
        case 'ping':
            // first byte indicates FIN, Ping frame (10001001):
            $frameHead[0] = 137;
            break;
        case 'pong':
            // first byte indicates FIN, Pong frame (10001010):
            $frameHead[0] = 138;
            break;
    }
    // set mask and payload length (using 1, 3 or 9 bytes)
    if ($payloadLength > 65535) {
        $payloadLengthBin = str_split(sprintf('%064b', $payloadLength), 8);
        $frameHead[1] = ($masked === true) ? 255 : 127;
        for ($i = 0; $i < 8; $i++) {
            $frameHead[$i + 2] = bindec($payloadLengthBin[$i]);
        }
        // most significant bit MUST be 0 (close connection if frame too big)
        if ($frameHead[2] > 127) {
            $this->close(1004);
            return false;
        }
    } elseif ($payloadLength > 125) {
        $payloadLengthBin = str_split(sprintf('%016b', $payloadLength), 8);
        $frameHead[1] = ($masked === true) ? 254 : 126;
        $frameHead[2] = bindec($payloadLengthBin[0]);
        $frameHead[3] = bindec($payloadLengthBin[1]);
    } else {
        $frameHead[1] = ($masked === true) ? $payloadLength + 128 : $payloadLength;
    }
    // convert frame-head to string:
    foreach (array_keys($frameHead) as $i) {
        $frameHead[$i] = chr($frameHead[$i]);
    }
    if ($masked === true) {
        // generate a random mask:
        $mask = array();
        for ($i = 0; $i < 4; $i++) {
            $mask[$i] = chr(rand(0, 255));
        }
        $frameHead = array_merge($frameHead, $mask);
    }
    $frame = implode('', $frameHead);
    // append payload to frame:
    for ($i = 0; $i < $payloadLength; $i++) {
        $frame .= ($masked === true) ? $payload[$i] ^ $mask[$i % 4] : $payload[$i];
    }
    return $frame;
}
?>

相关内容

  • 没有找到相关文章

最新更新