WebSocket規范的目標是在浏覽器中實現和服務器端雙向通信。雙向通信可以拓展浏覽器上的應用類型,如果你想要用PHP來寫websocket應用,那swoole_framework一定是最好的選擇,需要的朋友可以參考下
代碼如下: <?php define('DEBUG', 'on'); define("WEBPATH", str_replace("","/", __DIR__)); require __DIR__ . '/../libs/lib_config.php'; class WebSocket extends SwooleNetworkProtocolWebSocket { /** * 下線時,通知所有人 */ function onClose($serv, $client_id, $from_id) { //將下線消息發送給所有人 //$this->log("onOffline: " . $client_id); //$this->broadcast($client_id, "onOffline: " . $client_id); parent::onClose($serv, $client_id, $from_id); } /** * 接收到消息時 * @see WSProtocol::onMessage() */ function onMessage($client_id, $ws) { $this->log("onMessage: ".$client_id.' = '.$ws['message']); $this->send($client_id, "Server: ".$ws['message']); //$this->broadcast($client_id, $ws['message']); } function broadcast($client_id, $msg) { foreach ($this->connections as $clid => $info) { if ($client_id != $clid) { $this->send($clid, $msg); } } } } $AppSvr = new WebSocket(); $AppSvr->loadSetting(__DIR__."/swoole.ini"); //加載配置文件 $AppSvr->setLogger(new SwooleLogEchoLog(true)); //Logger $server = new SwooleNetworkServer('0.0.0.0', 9503); $server->setProtocol($AppSvr); //$server->daemonize(); //作為守護進程 $server->run(array('worker_num' =>4));