PHP code example of sanchescom / laravel-phpsocket.io

1. Go to this page and download the library: Download sanchescom/laravel-phpsocket.io 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/ */

    

sanchescom / laravel-phpsocket.io example snippets


'providers' => [
    ...
    App\Providers\SocketServiceProvider::class,
],

$app->register(App\Providers\SocketServiceProvider::class);
 php


namespace App\Providers;

use Sanchescom\LaravelSocketIO\SocketServiceProvider as ServiceProvider;
use App\Sockets\ExampleSocket;

/**
 * Class SocketServiceProvider.
 */
class SocketServiceProvider extends ServiceProvider
{
    /**
     * The socket handlers for the application.
     *
     * @var array
     */
    protected $sockets = [
        ExampleSocket::class,
    ];
}
 php


namespace App\Sockets;

use PHPSocketIO\SocketIO;
use Sanchescom\LaravelSocketIO\Sockets\AbstractSocket;
use Workerman\Lib\Timer;

class ExampleSocket extends AbstractSocket
{
    /**
     * @var int
     */
    const TIME_INTERVAL = 4;

    /**
     * @var int
     */
    protected $port = 2020;

    /**
     * @var array
     */
    protected $options = [];

    /**
     * @param SocketIO $socketIO
     */
    public function call(SocketIO $socketIO): void
    {
        $socketIO->on('workerStart', function () use ($socketIO) {
            Timer::add(self::TIME_INTERVAL, function () use ($socketIO) {
                $socketIO->to('room')->emit('score', [
                    'items' => [
                        [
                            'id' => 1,
                            'message' => 'Hello world'
                        ],
                    ]
                ]);
            });
        });

        $socketIO->on('connection', function ($socket) {
            $socket->join('room');
        });
    }
}