How to use PHP websockets (Ratchet) on Heroku

  heroku, nginx, php, ratchet, websocket

I made a chat in PHP backend in localhost and i would migrate my chat on heroku.
So till there it’s ok, i transfer files… , i run my php script with: heroku run bash php socket.php.
But when i connect to the websocket in js with that code: WebSocket('ws://xamchat.herokuapp.com:8889');
I have no answer, just a timeout.

Here’s my code for the socket:

<?php
 
require __DIR__.'/vendor/autoload.php';
 
use RatchetServerIoServer;
use RatchetHttpHttpServer;
use RatchetWebSocketWsServer;
use RatchetMessageComponentInterface;
use RatchetConnectionInterface;
 
 
define('APP_PORT', 8889);/*8889*/
 
 
 
 
 
class ServerImpl implements MessageComponentInterface {
    protected $clients;
 
    public function __construct() {
        $this->clients = new SplObjectStorage;
    }
 
    public function onOpen(ConnectionInterface $conn) {
        $this->clients->attach($conn);
        echo "New connection! ({$conn->resourceId}) [server]n";
    }
 
 
 
    public function onMessage(ConnectionInterface $conn, $msg) {
        echo sprintf("New message from '%s': %snnn", $conn->resourceId, $msg);
        $conn->send("received");
 
        foreach ($this->clients as $client) { // BROADCAST
            $message = json_decode($msg, true);
            if ($conn !== $client) {
                $client->send("new message:".$msg);
            }
        }
 
 
        $json = json_decode($msg);
 
        
 
     
 
    }
 
 
 
 
 
    public function onClose(ConnectionInterface $conn) {
        $this->clients->detach($conn);
        echo "Connection {$conn->resourceId} is gone.n";
    }
 
    public function onError(ConnectionInterface $conn, Exception $e) {
        echo "An error occured on connection {$conn->resourceId}: {$e->getMessage()}nnn";
        $conn->close();
    }
}
 
 
$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new ServerImpl()
        )
    ),
    APP_PORT
);
 
 
echo "Server created on port " . APP_PORT . "nn";
$server->run();
?>

It’s weird cause it’s like if the port was open but blocked.
I have no idea how to correct that.
Does anybody could help me ?
Thanks

Source: Ask PHP

LEAVE A COMMENT