PHP code example of mita / uranus-socket-server

1. Go to this page and download the library: Download mita/uranus-socket-server library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mita / uranus-socket-server example snippets




namespace Mita\UranusSocketServer\Examples\Chat\Controllers;

use Mita\UranusSocketServer\Controllers\BaseController;
use Mita\UranusSocketServer\Managers\ConnectionManager;
use Mita\UranusSocketServer\Packets\PacketInterface;
use Ratchet\ConnectionInterface;

class ChatController extends BaseController
{
    public function handle(ConnectionInterface $conn, PacketInterface $packet, array $params)
    {
        if ($params['_route'] === 'join_room') {
            $conn->send("You joined room " . $params['roomId']);
        } elseif ($params['_route'] === 'room_publish') {
            $conn->send("Message to room " . $params['roomId'] . ": " . $packet->getMessage());
        }
    }
}



use Mita\UranusSocketServer\SocketServer;

$settings = [
    'host' => '127.0.0.1',
    'port' => 7654,
    'router_path' => __DIR__ . '/routes.yaml'
];

$socketServer = new SocketServer($settings);
$socketServer->run();



use Mita\UranusSocketServer\Examples\ChatWithAuth\Plugins\AuthPlugin;
use Mita\UranusSocketServer\SocketServer;

$settings = [
    'host' => '127.0.0.1',
    'port' => 7654,
    'router_path' => __DIR__ . '/routes.yaml'
];

$socketServer = new SocketServer($settings);

$authPlugin = new AuthPlugin('your_secret_key');
$socketServer->addPlugin($authPlugin);

$socketServer->run();

class AuthPlugin implements PluginInterface, MiddlewareInterface
{
    protected $secretKey;
    protected $keyName;

    // 1. Constructor
    public function __construct($secretKey, $keyName = 'access_token')
    {
        $this->secretKey = $secretKey;
        $this->keyName = $keyName;
    }

    // 2. Registering the Plugin
    public function register(EventDispatcherInterface $dispatcher)
    {
        $dispatcher->addListener('middleware.register', [$this, 'onRegisterMiddleware']);
        $dispatcher->addListener('connection.open', [$this, 'onOpen']);
    }

    // 3. Register Middleware
    public function onRegisterMiddleware(MiddlewarePipeline $pipeline)
    {
        $pipeline->add($this);
    }

    // 4. Connection Open Handler
    public function onOpen(ConnectionInterface $conn)
    {
        $uri = $conn->httpRequest->getUri();
        parse_str($uri->getQuery(), $params);
        $token = $params[$this->keyName] ?? null;
        
        if (!$this->validateToken($token)) {
            $conn->send("Invalid token");
            $conn->close();
            throw new \Exception("Invalid token");
        }
    }

    // 5. Message Handler Middleware
    public function handle(ConnectionInterface $conn, PacketInterface $packet, callable $next)
    {
        $token = $packet->getMetadata($this->keyName);

        if (!$this->validateToken($token)) {
            $conn->send("Invalid token");
            $conn->close();
            return;
        }

        $next($conn, $packet);
    }

    // 6. Token Validation Method
    protected function validateToken($token)
    {
        if (!$token) {
            return false;
        }

        return $token == $this->secretKey;
    }
}

  public function run()
  

  public function registerEventListener(string $eventName, callable $listener)
  

  public function handle(ConnectionInterface $conn, PacketInterface $packet, callable $next)
  

  public function add(MiddlewareInterface $middleware)
  

  public function process(ConnectionInterface $conn, PacketInterface $packet, callable $finalHandler)
  

  public function add(ConnectionInterface $conn)
  

  public function remove(ConnectionInterface $conn)
  

  public function addListener(string $eventName, callable $listener)
  

  public function dispatch(string $eventName, $eventData = null)
  

  public function getRoute(): string
  

  public function getMessage()
  

  public function getMetadata(string $key = null)
  

  public function createFromJson(string $json): PacketInterface
  

  public function addPlugin(PluginInterface $plugin)
  

  public function registerPlugins(EventDispatcherInterface $dispatcher)
  

  public function bootPlugins()
  

  use Mita\UranusSocketServer\Events\EventDispatcherInterface;
  use Mita\UranusSocketServer\Plugins\PluginInterface;

  class MyCustomPlugin implements PluginInterface
  {
      public function register(EventDispatcherInterface $dispatcher)
      {
          // Register events or middleware here
      }

      public function boot()
      {
          // Code to run when the plugin is booted
      }

      public function unregister(EventDispatcherInterface $dispatcher)
      {
          // Unregister events or middleware here
      }
  }
  

  $myPlugin = new MyCustomPlugin();
  $socketServer->addPlugin($myPlugin);
  

     $socketServer->registerEventListener('connection.opened', function($conn) {
         echo "New connection opened with ID: " . $conn->resourceId . "\n";
     });
     

     $socketServer->registerEventListener('message.received', function($data) {
         $conn = $data['connection'];
         $msg = $data['message'];
         echo "Message received from connection {$conn->resourceId}: {$msg}\n";
     });
     

     $socketServer->registerEventListener('plugin.registered', function($plugin) {
         echo "Plugin registered: " . get_class($plugin) . "\n";
     });
     

     $socketServer->registerEventListener('connection.added', function($conn) {
         echo "Connection added with ID: " . $conn->resourceId . "\n";
     });
     

     $socketServer->registerEventListener('connection.removed', function($conn) {
         echo "Connection removed with ID: " . $conn->resourceId . "\n";
     });
     

     $socketServer->registerEventListener('connection.subscribed', function($data) {
         $conn = $data['conn'];
         $route = $data['route'];
         echo "Connection {$conn->resourceId} subscribed to route: {$route}\n";
     });
     

     $socketServer->registerEventListener('connection.unsubscribed', function($data) {
         $conn = $data['conn'];
         $route = $data['route'];
         echo "Connection {$conn->resourceId} unsubscribed from route: {$route}\n";
     });
     

     $socketServer->registerEventListener('message.sent', function($data) {
         $route = $data['route'];
         $message = $data['message'];
         echo "Message sent to route {$route}: {$message}\n";
     });
     
bash
php index.php
bash
php index.php
plaintext
ws://127.0.0.1:7654/?access_token=your_secret_key