PHP code example of cydrickn / swoole-websocket-bundle

1. Go to this page and download the library: Download cydrickn/swoole-websocket-bundle 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/ */

    

cydrickn / swoole-websocket-bundle example snippets


#!/usr/bin/env php


use App\Kernel;

$_SERVER['APP_RUNTIME_OPTIONS'] = [
    'host' => '0.0.0.0',
    'port' => 8000,
    'mode' => SWOOLE_PROCESS,
    'settings' => [
        \Swoole\Constant::OPTION_WORKER_NUM => swoole_cpu_num() * 2,
        \Swoole\Constant::OPTION_ENABLE_STATIC_HANDLER => true,
        \Swoole\Constant::OPTION_DOCUMENT_ROOT => dirname(__DIR__).'/public'
    ],
];


$_SERVER['APP_RUNTIME_OPTIONS'] = [
    'host' => '0.0.0.0',
    'port' => 8000,
    'mode' => SWOOLE_PROCESS,
    'hotReload'=> [
        'enabled' => true,
        'basePath' => dirname(__DIR__),
    ],
    'settings' => [
        \Swoole\Constant::OPTION_WORKER_NUM => swoole_cpu_num() * 2,
        \Swoole\Constant::OPTION_ENABLE_STATIC_HANDLER => true,
    ],
];

$_SERVER['APP_RUNTIME_OPTIONS'] = [
    'socketio' => true,
    'host' => '0.0.0.0',
    'port' => 8000,
    'mode' => SWOOLE_PROCESS,
    'settings' => [
        \Swoole\Constant::OPTION_WORKER_NUM => swoole_cpu_num() * 2,
        \Swoole\Constant::OPTION_ENABLE_STATIC_HANDLER => true,
    ],
];

$server->on('connection', function (\Cydrickn\SocketIO\Socket $socket) {
    $socket->emit('hello', 'world');
});

$server->on('chat', function (\Cydrickn\SocketIO\Socket $socket, $message) {
    $socket->broadcast()->emit('chat', $message);
});


namespace App\Controller;

use Cydrickn\SwooleWebsocketBundle\Attribute\RouteAttribute;

class SocketController
{
   #[RouteAttribute(path: 'connection')]
   public function connection(\Cydrickn\SocketIO\Socket $socket)
   {
      $socket->emit('hello', 'world');
   }
   
   #[RouteAttribute(path: 'chat')]
   public function anotherMethod(\Cydrickn\SocketIO\Socket $socket, $message)
   {
      $socket->broadcast()->emit('chat', $message);
   }
}
shell
php ./bin/console websocket:server
shell
   APP_RUNTIME=\\Cydrickn\\SwooleWebsocketBundle\\Runtime\\Runtime php ./public/index.php
   
shell
composer