How do I keep a websocket server running, even after I close the SSH terminal?

Lucas picture Lucas · Oct 21, 2013 · Viewed 9.5k times · Source

So, I am using Ratchet with PHP, and have currently uploaded a successful websocket example to my server.

It works after I go to SSH, and then just manually run "php bin/chat-server.php".

What I was wondering is that, in a commercial situation, how do I keep the chat server running?

Thanks.

Answer

mattexx picture mattexx · Oct 21, 2013

Make a daemon.

If you are using symfony2, you can use the Process Component.

// in your server start command
$process = new Process('/usr/bin/php bin/chat-server.php');
$process->start();
sleep(1);
if ($process->isRunning()) {
    echo "Server started.\n";
} else {
    echo $process->getErrorOutput();
}

// in your server stop command
$process = new Process('ps ax | grep bin/chat-server.php');
$process->run();
$output = $process->getOutput();
$lines = preg_split('/\n/', $output);
// kill everything (there can be multiple processes if they are spawned)
$stopped = False;
foreach ($lines as $line) {
    $ar = preg_split('/\s+/', trim($line));
    if (in_array('/usr/bin/php', $ar)
        and in_array('bin/chat-server.php', $ar)) {
        $pid = (int) $ar[0];
        posix_kill($pid, SIGKILL);
        $stopped = True;
    }
}
if ($stopped) {
    echo "Server stopped.\n";
} else {
    echo "Server not found. Are you sure it's running?\n";
}

If you are using native PHP, never fear, popen is your friend!

// in your server start command
_ = popen('/usr/bin/php bin/chat-server.php', 'r');
echo "Server started.\n";

// in your server stop command
$output = array();
exec('ps ax | grep bin/chat-server.php', &$output);
$lines = preg_split('/\n/', $output);
// kill everything (there can be multiple processes if they are spawned)
$stopped = False;
foreach ($lines as $line) {
    $ar = preg_split('/\s+/', trim($line));
    if (in_array('/usr/bin/php', $ar)
        and in_array('bin/chat-server.php', $ar)) {
        $pid = (int) $ar[0];
        posix_kill($pid, SIGKILL);
        $stopped = True;
    }
}
if ($stopped) {
    echo "Server stopped.\n";
} else {
    echo "Server not found. Are you sure it's running?\n";
}

There are of course also other helpful PHP libraries for working with daemons. Googling "php daemon" will give you a lot of pointers.