【问题标题】:Run Ratchet php server without need of cli无需 cli 即可运行 Ratchet php 服务器
【发布时间】:2019-07-12 01:06:23
【问题描述】:

我正在与Ratchet 实现 websocket 实时聊天 它工作正常,问题是我需要通过命令行运行 server.php 所以这样服务器才能工作,我不能直接运行文件 我试过了:

执行()

还有其他方法但无法运行服务器,有没有人有替代方案或解决方案?

服务器.php

<?php

use Ratchet\Http\HttpServer;
use Ratchet\Server\IoServer;
use Ratchet\WebSocket\WsServer;

   
require 'vendor/autoload.php';
require 'class/SimpleChat.php';

   
$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new SimpleChat()
        )
    ),
    8080
);

$server->run();

/class/SimpleChat.php

<?php

use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class SimpleChat implements MessageComponentInterface
{
    /** @var SplObjectStorage  */
    protected $clients;

    /**
     * SimpleChat constructor.
     */
    public function __construct()
    {
        conectados
        $this->clients = new \SplObjectStorage;
    }

    /**
     * @param ConnectionInterface $conn
     */
    public function onOpen(ConnectionInterface $conn)
    {
       
        $this->clients->attach($conn);
        echo "Cliente conectado ({$conn->resourceId})" . PHP_EOL;
    }

    /**
     * @param ConnectionInterface $from
     * @param string $data
     */
    public function onMessage(ConnectionInterface $from, $data)
    {
        
        $data = json_decode($data);
        $data->date = date('d/m/Y H:i:s');

        
        foreach ($this->clients as $client) {
            $client->send(json_encode($data));
        }

        echo "User {$from->resourceId} sent you a message" . PHP_EOL;
    }

    /**
     * @param ConnectionInterface $conn
     */
    public function onClose(ConnectionInterface $conn)
    {
        $this->clients->detach($conn);
        echo "User {$conn->resourceId} Disconnected" . PHP_EOL;
    }

    /**
     * @param ConnectionInterface $conn
     * @param Exception $e
     */
    public function onError(ConnectionInterface $conn, \Exception $e)
    {
        
        $conn->close();

        echo "Error {$e->getMessage()}" . PHP_EOL;
    }
}

【问题讨论】:

    标签: php websocket command-line-interface ratchet phpwebsocket


    【解决方案1】:

    我也遇到过同样的问题。使用 cURL 解决了它。使用以下命令 无需 cli 即可启动棘轮服务器。

    $handle = curl_init();
     $url = 'Path-to-your-server-file/App/server.php';
     curl_setopt($handle,CURLOPT_URL,$url);
     curl_setopt($handle, CURLOPT_TIMEOUT, 1); 
     $data = curl_exec($handle);
     curl_close($handle);
     print_r($handle);
    

    【讨论】:

      猜你喜欢
      • 2015-04-13
      • 1970-01-01
      • 1970-01-01
      • 2015-12-23
      • 1970-01-01
      • 2011-04-25
      • 1970-01-01
      • 2015-04-02
      • 2019-07-04
      相关资源
      最近更新 更多