10

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

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

php -q myserver.php

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

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

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

这可能吗?

4

1 回答 1

4

是的,这是可能的,但你应该看看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所以你也可以看看下面

于 2012-10-15T11:15:35.130 回答