Reputation: 1558
I am implementing a websocket real time chat with Ratchet It's working fine, The problem is that I need to run server.php via command line so this way the server will work, I can not run the file directly I tried via:
exec()
And other methods but it fails to run the server, anyone have an alternative or a solution?
server.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;
}
}
Upvotes: 0
Views: 847
Reputation: 41
I have been into the same problem. Solved it using cURL. Use the following command to start ratchet server without the need of 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);
Upvotes: 3