Ratchet
Ratchet copied to clipboard
Fail Deploying Ratchet on Heroku
Hi, i have just migrated my chat project on heroku but i can not connect to the ws server. I typed that command on the remote shell of heroku like usually "php socket.php" But when i connect to the server, no answers... Here's the code of socket.php
`<?php
require __DIR__.'/vendor/autoload.php';
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
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': %s\n\n\n", $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()}\n\n\n";
$conn->close();
}
}
$server = IoServer::factory(
new HttpServer(
new WsServer(
new ServerImpl()
)
),
APP_PORT
);
echo "Server created on port " . APP_PORT . "\n\n";
$server->run();
?>`
So to connect with js to the server i use: var conn = new WebSocket('ws://xamchat.herokuapp.com:8889');
Thanks for help
Hi, you have to use port that is stored in environment variable.
Like this define('APP_PORT', getenv('PORT'));
And than connect to it on port 80 because its running on dyno and there is some kind of router.
So script like this var conn = new WebSocket('ws://xamchat.herokuapp.com');
You should use Procfile to start server
Like this web: php server.php -p $PORT
Hope it helps :)