首页 > 解决方案 > PHP 流套接字:页面加载时与 wss://host:port 的连接中断

问题描述

我在使用 PHP 编写的从 Firefox 到我的服务器的 Web 套接字连接/握手时遇到问题。问题是当我尝试连接客户端(使用 js/php 甚至 websocket.org/echo.html)时出现问题,问题是客户端首先连接然后自动断开连接。在服务器上,我fwrite用来向客户端发送消息。而且我还注意到,对于来自 firefox 的客户端作为响应fwrite返回,但在客户端我可以看到服务器已经发布了握手数据。0

现在我看到问题出在这里,当服务器正在写入但响应0仍然存在并且浏览器(firefox)仍在获得响应但它同时与服务器断开连接时。我什至尝试以字节为单位比较(计算)数据,哪个服务器正在发布到客户端。我看完全一样。

注意:- 只是在这里提一下,相同的 php 服务器脚本在 Opera/Chrome/Safari 浏览器上运行良好。

以下是此问题所涉及的内容;

# STREAM SOCKET CREATION OVER SSL(WSS)
$context = stream_context_create(); 
stream_context_set_option($context, 'ssl', 'local_cert', 'ssl-test.pem'); #change to your own ssl.pem path
stream_context_set_option($context, 'ssl', 'allow_self_signed', true); 
stream_context_set_option($context, 'ssl', 'verify_peer', false); 
$sock = stream_socket_server("ssl://".HOST_NAME.":".PORT,$errno,$errstr,STREAM_SERVER_BIND|STREAM_SERVER_LISTEN, $context) or die('Unable to start server, seems server is already running!'); 
// stream_set_blocking($sock,TRUE);


# PUTTING ALL(CURRENT/UPCOMING) SOCKET CONNECTIONS IN ARRAY
$clients = array();

# INFINTE LOOP THOURGH ALL SOCKECT CURRENT/UPCOMING CONNECTIONS, SEND/RECEIVE DATA
while (true) {

    # ALL ACTIVE SOCKET CONNECTIONS
    $read = $clients;

    foreach($received_header as $key => $header){
        if($header['time']+1 < microtime(true)){
            $headers  = [];
            // echo $header['data'];
            $lines    = preg_split("/\r\n/", $header['data']);
            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')));

            // create handshake header
            $upgrade  = "HTTP/1.1 101 Web Socket Protocol Handshake" .PHP_EOL.
            "Upgrade: websocket" .PHP_EOL.
            "Connection: Upgrade" .PHP_EOL.
            "Accept: text/html" .PHP_EOL.
            "Sec-WebSocket-Accept: $secAccept".PHP_EOL.PHP_EOL;

            // send handshake packet
            if(!fwrite($clients[$key], $upgrade)){
                file_put_contents('handshakes-est.txt', ($upgrade));
            }



            $handshakes[$key] = true;
            $unset_key = $key;
        }
    }
/* i have rest of the script here which do further communication after connection is setup */
}

下面是一些屏幕截图,以更好地了解 Firefox 上的连接行为问题。

握手期间的标头: 握手期间的标头

通过 websocket 的连接行为: 通过 websocket 的连接行为

标签: phpfirefoxphpwebsocket

解决方案


推荐阅读