Websocket在Firefox上运行良好,但在Chrome中运行良好

时间:2014-08-20 13:28:45

标签: php google-chrome firefox amazon-web-services websocket

我在aws ec2中设置了一个websocket服务器,使用php套接字,使用我的dns作为ws url,如:

var websocket = new WebSocket('ws://ec2-177-71-x-x.sa-east-1.compute.amazonaws.com:60997');

这是firefox控制台中的Request:

Host: ec2-177-71-x-x.sa-east-1.compute.amazonaws.com:60997
User-Agent: Mozilla/5.0 (X11; Linux i686; rv:26.0) Gecko/20100101 Firefox/26.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Sec-WebSocket-Version: 13
Origin: http://localhost
Sec-WebSocket-Key: csxgGFmTuJYxgvfsbgKtyA==
Connection: keep-alive, Upgrade
Pragma: no-cache
Cache-Control: no-cache
Upgrade: websocket

响应:

Connection: "Upgrade"
Sec-WebSocket-Accept: "AmwLLFdVkE9buCccH1oggz4FNJM="
Upgrade: "websocket"
WebSocket-Location: "ws://ec2-177-71-x-x.sa-east-1.compute.amazonaws.com:60997"
WebSocket-Origin: "ec2-177-71-x-x.sa-east-1.compute.amazonaws.com"

似乎Google Chrome无法访问websocket服务器,我尝试将网址放在http://www.websocket.org/echo.html中,但只有firefox连接。

我猜问题可能是握手,这是我正在使用的功能

//handshake new client.
function perform_handshaking($receved_header,$client_conn, $host, $port)
{
    var_dump($receved_header);
    $headers = array();
    $lines = preg_split("/\r\n/", $receved_header);
    foreach($lines as $line)
    {
        $line = chop($line);
        if(preg_match('/\A(\S+): (.*)\z/', $line, $matches))
        {
            $headers[$matches[1]] = $matches[2];
        }
    }

    $secKey = $headers['Sec-WebSocket-Key'];

    $secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
    //hand shaking header
    $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:$port\r\n".
    "Sec-WebSocket-Accept:$secAccept\r\n\r\n";
    var_dump(socket_write($client_conn,$upgrade,strlen($upgrade)));
}

附加信息:我在本地和测试服务器上设置了相同的websocket,这是一台带有php 5.4+的Centos 6.0机器,并且在chrome和firefox中运行良好。 生产服务器中出现问题的php版本是:PHP 5.3.27

1 个答案:

答案 0 :(得分:0)

问题解决:Squid不支持协议升级websocket连接代理,如果websocket失败,firefox会尝试进行协议连接