Moisés Moisés - 9 months ago 161
PHP Question

WebSocket with Laravel 5.2

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

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

Someone knows if it is possible to make this server as a controller or at least have acess to the database throught 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
});

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download