📜  laravel 8 websockets - PHP (1)

📅  最后修改于: 2023-12-03 15:32:32.603000             🧑  作者: Mango

Laravel 8 Websockets - PHP

Laravel 8 Websockets is a package that allows real-time communication between server and clients in Laravel using websockets. It is built on top of Ratchet, a PHP websocket library, and is designed to be easy to use and flexible for any real-time application.

Installation

To install Laravel 8 Websockets, run the following command in your Laravel project:

composer require beyondcode/laravel-websockets

Once installed, Laravel 8 Websockets provides a websockets:install Artisan command. This command will publish the configuration file, migration, and WebSocket server file.

php artisan websockets:install
Configuration

The configuration file for Laravel 8 Websockets is located in the config/websockets.php file. This file allows you to configure the WebSocket server address, port, and SSL settings.

'websocket' => [
    'middleware' => ['auth:api'],
    'route' => '/websocket',
    'handler' => \BeyondCode\LaravelWebSockets\WebSockets\WebSocketHandler::class,
    'use_app_routes' => true,
    'app_route_prefix' => '',
    'ping_interval_in_seconds' => 30,
    'ping_timeout_in_seconds' => 5,
    'allow_unauthorized' => false,
    'max_request_size_in_kb' => 250,
    'max_connections' => 5000,
    'ssl' => [
        'local_cert' => '',
        'local_pk' => '',
        'passphrase' => '',
    ],
],
Broadcasting Events

To broadcast events using Laravel 8 Websockets, you can use the broadcast method on the event class. This method will automatically determine if the event should be broadcasted to WebSocket clients or not.

broadcast(new OrderShipped($order));
Listening for Events

To listen for events on the client side, you can use JavaScript to connect to the Laravel 8 Websockets server and subscribe to a channel.

const websocket = new WebSocket('ws://localhost:6001');

websocket.addEventListener('open', () => {
    websocket.send(JSON.stringify({
        event: 'subscribe',
        channel: 'order.1'
    }));
});

websocket.addEventListener('message', event => {
    console.log(JSON.parse(event.data));
});
Conclusion

Laravel 8 Websockets is a powerful package for real-time communication between server and clients in Laravel. It is easy to use and flexible for any real-time application. With this package, you will be able to create real-time applications that are fast, reliable, and scalable.