从第一个客户端请求启动php中的websocket服务器

时间:2012-10-15 11:04:40

标签: php websocket

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

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

php -q myserver.php

我试图获取的是当我第一次连接客户端时使用服务器,并将此服务器用于所有其他客户端,而不使用命令行

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

此命令如果服务器未运行,我想运行服务器并打开此客户端的连接。

这可能吗?

1 个答案:

答案 0 :(得分:2)

是的,但是你应该看看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,因此您还可以查看以下内容