phplaravelwebsocketlaravel-5

WebSocket with Laravel 5.2


I'm doing a application in Laravel 5.2 that uses websockets. For the websocket connection I'm using HoaServer, which works very well.

The bad part is, I do not know how to make this server as a controller, or at least have access to my models, right now I'm using a separated PDO connection to make the DB queries.

Someone knows if it is possible to make this server as a controller or at least have access to the database through Laravel models?

My server right now:

require_once(__DIR__.'/../vendor/autoload.php');

$PDO = new PDO('mysql:host=127.0.0.1:3306;dbname=DBNAME', "USER", "PASS");

$websocket = new Hoa\Websocket\Server(new Hoa\Socket\Server('ws://'.$ip.':'.$porta));

$websocket->on('open', function (Hoa\Event\Bucket $bucket) {
    return;
});

$websocket->on('message', function (Hoa\Event\Bucket $bucket) {
    return;
});

$websocket->on('close', function (Hoa\Event\Bucket $bucket) {
    return;
});

$websocket->run();

The closest that I fond was to fire an laravel event, that I do not know how.

//Socket server message event
$server->on('message', function() {
     //Fire your Laravel Event here
});

Solution

  • I think that what you should do is to create a console command.

    php artisan make:console StartSocketServer  --command=socket:start
    

    and then you edit the generated class as follows

    <?php
    
    namespace App\Console\Commands;
    
    use Illuminate\Console\Command;
    
    class StartSocketServer extends Command
    {
        /**
         * The name and signature of the console command.
         *
         * @var string
         */
        protected $signature = 'socket:start';
    
        /**
         * The console command description.
         *
         * @var string
         */
        protected $description = 'start the socket server';
    
        /**
         * Create a new command instance.
         */
        public function __construct()
        {
            parent::__construct();
        }
    
        /**
         * Execute the console command.
         *
         * @return mixed
         */
        public function handle()
        {
            $websocket = new Hoa\Websocket\Server(new Hoa\Socket\Server('ws://'.$ip.':'.$porta));
    
            $websocket->on('open', function (Hoa\Event\Bucket $bucket) {
              return;
            });
    
            $websocket->on('message', function (Hoa\Event\Bucket $bucket) {
              return;
            });
    
            $websocket->on('close', function (Hoa\Event\Bucket $bucket) {
              return;
            });
    
            $websocket->run();
        }
    }
    

    Finally after registering the command in App\Console\Kernel you can run php artisan socket:start from your terminal.

    I never used HoaServer , But i think this should work.