Skip to content
Advertisement

How to Keep a Ratchet WebSocket alive?

I have a Ratchet (PHP Real-Time Class) project on my localhost. When I want to use and test this project,
I run CMD and use this command: C:wampwwwChatApp> php cmd.php (cmd.php is websocket launcher). and when i press Ctrl + C or exit cmd, this websocket dies.

but, what can i do when i transfer project to main host to alive this websocket?

cmd.php:

require 'vendor/autoload.php';

use RatchetServerIoServer;
use RatchetHttpHttpServer;
use RatchetWebSocketWsServer;
require 'Chat.php';

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

$server->run();


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

$server->run();

Chat.php (Class):

namespace ChatApp;

use RatchetMessageComponentInterface;
use RatchetConnectionInterface;

class Chat implements MessageComponentInterface {
    protected $clients;

    public function __construct() {
        $this->clients = new SplObjectStorage();
    }

    public function onOpen(ConnectionInterface $conn) {
        $this->clients->attach($conn);
        echo 'Someone Connected'.PHP_EOL;
    }

    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 'Someone Has Disconnected'.PHP_EOL;
    }

    public function onError(ConnectionInterface $conn, Exception $e) {
        echo "An Error Has Occurred: {$e->getMessage()}n";
        $conn->close();
    }
}

Advertisement

Answer

You can use ( nohup ) command in linux . Write this code in your server.php root

nohup php server.php

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement