PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, April 12, 2022

[FIXED] How to Keep a Ratchet WebSocket alive?

 April 12, 2022     php, phpwebsocket, ratchet, real-time, websocket     No comments   

Issue

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:\wamp\www\ChatApp> 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 Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
require 'Chat.php';

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

$server->run();


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

$server->run();

Chat.php (Class):

namespace ChatApp;

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 '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();
    }
}

Solution

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

nohup php server.php



Answered By - you pro
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing