我正在尝试在我的本地 WAMP 服务器上设置网络套接字,我已经关注了几个文档,现在我正处于这一点。我首先安装了composer然后为PHP安装了Ratchet,然后我创建了2个PHP文件:
server.php
:
<?php
require 'Chat.php';
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Chat;
require dirname(__DIR__) . '/www/vendor/autoload.php';
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
),
8080
);
$server->run();
Chat.php
:
<?php
namespace MyApp;
require 'vendor/autoload.php';
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface
{
protected $clients;
public function __construct()
{
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn)
{
$this->clients->attach($conn);
echo "Nouvelle connexion : ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $msg)
{
foreach ($this->clients as $client) {
if ($from !== $client) {
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn)
{
$this->clients->detach($conn);
echo "Connexion fermée : ({$conn->resourceId})\n";
}
public function onError(ConnectionInterface $conn, \Exception $e)
{
echo "Erreur : ({$conn->resourceId}) : {$e->getMessage()}\n";
$conn->close();
}
}
最后,我打开我的CMD并运行:
php server.php
Starting WebSocket server on: 0.0.0.0:8080
就好像程序在循环运行一样,像一个while循环。如何解决问题?