Skip to content

Instantly share code, notes, and snippets.

@gensart-x
Last active December 31, 2025 17:37
Show Gist options
  • Select an option

  • Save gensart-x/a9dc8464e229d25c514c3e239e438229 to your computer and use it in GitHub Desktop.

Select an option

Save gensart-x/a9dc8464e229d25c514c3e239e438229 to your computer and use it in GitHub Desktop.
Bare Setup WebSocket server in CodeIgniter 4 - PHP 8
<?php
namespace App\Libraries;
use CodeIgniter\CLI\CLI;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class WebSocket implements MessageComponentInterface
{
protected $clients;
public function __construct()
{
$this->clients = [];
}
public function onOpen(ConnectionInterface $conn)
{
CLI::write('> Incoming new WebSocket connection');
// Getting the query to know where the connection is come from
// $query = $conn->httpRequest->getUri()->getQuery();
// if ($query != null) {
// // Parsing the query
// parse_str($query, $result);
// $params = array_keys($result);
// if (in_array('session_id', $params)) {
// }
// } else {
// // If the connection is not providing a valid query, reject the connection
// CLI::write('No query');
// $conn->close();
// return;
// }
// Store the new connection
$this->clients[$conn->resourceId] = $conn;
}
public function onMessage(ConnectionInterface $from, $msg)
{
// You handle incoming message from connection(s) here. I don't care what it is.
$packet = json_decode($msg, true);
if ($packet == null) {
CLI::write('> Invalid packet data (not JSON), ignored.', 'warning');
return;
}
$from->send(json_encode([
'message' => 'well, this is a response'
]));
}
public function onClose(ConnectionInterface $conn)
{
// The connection is closed, remove it, as we can no longer send it messages.
// This usually because of browser page closed, refreshed, or connection detached.
unset($this->clients[$conn->resourceId]);
CLI::print("Connection {$conn->resourceId} has disconnected" . PHP_EOL);
}
public function onError(ConnectionInterface $conn, \Exception $e)
{
// When something is occurred not normally.
// Usually you close the connection, but whatever to you, i'm not your father.
CLI::print('> An error has occurred: ' . $e->getMessage() . PHP_EOL . $e->getTraceAsString() . PHP_EOL);
$conn->close();
}
}
<?php
namespace App\Commands;
use App\Libraries\WebSocket;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
class WebSocketServer extends BaseCommand
{
/**
* The Command's Group
*
* @var string
*/
protected $group = 'App';
/**
* The Command's Name
*
* @var string
*/
protected $name = 'ws:server';
/**
* Actually execute a command.
*
* @param array $params
*/
public function run(array $params)
{
CLI::write('> WebSocket Server for Realtime Data Updates', 'green');
if (empty($params['port'])) {
CLI::write('> No port specified, defaulting to 8081', 'yellow');
CLI::write('> Use --port [PORT] argument to specify the port. Don\'t use the same as the app port!', 'yellow');
}
// If you aren't using CI 4, this below is the core of the functionality
$server = IoServer::factory(
new HttpServer(
new WsServer(
new WebSocket
)
),
$params['port'] ??= 8081 // port of the ws, don't set it to 65537, since it won't work.
);
CLI::write('> WebSocket Server running on port ' . $params['port'] . '...', 'green');
// And this one too, the rest is CI4-boilerplate codes.
$server->run();
}
}
@gensart-x
Copy link
Author

Installation:

  1. i use composer and CodeIgniter 4 of course.
  2. don't 4get to install the lib of ws, composer require cboden/ratchet
  3. copy the ...Command.php file to app/Commands and the other one is to app/Libraries
  4. run the ws by using php spark ws:server [--port <WS-PORT-IF-NEEDED>]
  5. boom 💥

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment