【问题标题】:start a websocket server in php from the first client request从第一个客户端请求在 php 中启动 websocket 服务器
【发布时间】:2012-10-15 11:04:40
【问题描述】:

我正在尝试使用 websocket 来替换对服务器的常量 ajax 请求,以更新 ajax 信息。

据我所知,在客户端-服务器场景中,我应该从命令行启动一个 php websocket 服务器:

php -q myserver.php

我想要获得的是在我的客户端第一次连接时启动服务器,并将此服务器用于所有其他客户端,不使用命令行

var socket = new WebSocket("ws://localhost:10000/myserver.php");

如果服务器没有运行,我想运行这个命令并为这个客户端打开一个连接。

这可能吗?

【问题讨论】:

    标签: php websocket


    【解决方案1】:

    是的,这是可能的,但你应该看看phpwebsocket

    var host = "ws://localhost:10000/myserver.php";
    try{
      socket = new WebSocket(host);
      log('WebSocket - status '+socket.readyState);
      socket.onopen    = function(msg){ log("Welcome - status "+this.readyState); };
      socket.onmessage = function(msg){ log("Received: "+msg.data); };
      socket.onclose   = function(msg){ log("Disconnected - status "+this.readyState); };
    }
    catch(ex){ log(ex); }
    

    你运行的服务器端php -q myserver.php

    log("Handshaking...");
    list($resource,$host,$origin) = getheaders($buffer);
    $upgrade = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
            "Upgrade: WebSocket\r\n" .
            "Connection: Upgrade\r\n" .
            "WebSocket-Origin: " . $origin . "\r\n" .
            "WebSocket-Location: ws://" . $host . $resource . "\r\n" .
            "\r\n";
    $handshake = true;
    socket_write($socket,$upgrade.chr(0),strlen($upgrade.chr(0)));
    

    phpwebsocket默认不支持RFC-6455所以你也可以看看下面

    【讨论】:

    • 看一眼代码表明 phpwebsocket 似乎只支持已弃用的 Websockets 的 Hixie-76 变体。这不适用于大多数浏览器。我是否缺少对较新的 RFC6455 格式的支持?如果没有,最好不要推荐使用 phpwebsocket。
    • 我只是看看php socket它需要命令行运行:从命令行,运行server.php程序来监听socket连接。
    • @simonc 可以使用 pack pack('C2a*', 0b10000001, 0b01111111 & strlen($upgrade.chr(0)), $upgrade.chr(0)); 轻松修复,但同样好的观察结果我会用其他替代方法更新我的答案,默认情况下支持RFC-6455
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-21
    • 1970-01-01
    • 2016-02-27
    • 2012-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多