Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Websocket Bundle Laravel Package

bordeux/websocket-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require bordeux/websocket-bundle
    

    Ensure compatibility with Symfony 3.x (this bundle is archived and may not support newer versions).

  2. Register the Bundle: Add to app/AppKernel.php:

    public function registerBundles()
    {
        $bundles = [
            // ...
            new Bordeux\WebsocketBundle\BordeuxWebsocketBundle(),
        ];
    }
    
  3. Start the WebSocket Server:

    php app/console bordeux:websocket:bundle
    

    Run this in a terminal to keep the WebSocket server alive.


First Use Case: Basic WebSocket Endpoint

Create a WebSocket controller (e.g., src/Acme/DemoBundle/Websocket/DemoWebsocket.php):

namespace Acme\DemoBundle\Websocket;

use Bordeux\WebsocketBundle\Websocket\Websocket;

class DemoWebsocket extends Websocket
{
    public function configureRoutes(RouteCollection $collection)
    {
        $collection->add('demo_ws', new Route('/ws/demo', []));
    }

    public function onOpen(Client $client)
    {
        $client->send(new Message('Connected!'));
    }

    public function onMessage(Client $client, Message $message)
    {
        $client->send(new Message('You said: ' . $message->getPayload()));
    }
}
  • Route: /ws/demo (adjust in configureRoutes).
  • Test: Use a WebSocket client (e.g., browser JS or Postman) to connect to ws://yourdomain.com/ws/demo.

Implementation Patterns

1. Controller Structure

  • File Location: Must follow <YourBundle>/Websocket/<Name>Websocket.php.
  • Key Methods:
    • configureRoutes(RouteCollection): Define WebSocket routes (e.g., /ws/user/{id}).
    • onOpen(Client): Handle new connections (e.g., send welcome message).
    • onMessage(Client, Message): Process incoming messages.
    • onClose(Client): Cleanup on disconnection.

2. Routing and Authentication

  • Dynamic Routes: Use route parameters (e.g., {id}) for user-specific WebSockets.
    $collection->add('user_ws', new Route('/ws/user/{id}', [], ['id' => '\d+']));
    
  • Authentication: Validate tokens in onOpen:
    public function onOpen(Client $client)
    {
        $request = $client->getRequest();
        $token = $request->query->get('token');
        if (!$this->isValidToken($token)) {
            $client->close();
            return;
        }
        $client->send(new Message('Authenticated!'));
    }
    

3. Broadcasting to Clients

  • Store Clients: Use a static array or service to track active clients:
    private static $clients = [];
    
    public function onOpen(Client $client)
    {
        self::$clients[$client->getId()] = $client;
    }
    
    public function broadcast(Message $message)
    {
        foreach (self::$clients as $client) {
            $client->send($message);
        }
    }
    
  • Targeted Messages: Filter clients by route parameters or metadata.

4. Integration with Symfony Services

  • Dependency Injection: Inject services (e.g., EntityManager) into the WebSocket class:
    use Symfony\Component\DependencyInjection\ContainerInterface;
    
    class DemoWebsocket extends Websocket
    {
        private $container;
    
        public function __construct(ContainerInterface $container)
        {
            $this->container = $container;
        }
    
        public function onMessage(Client $client, Message $message)
        {
            $em = $this->container->get('doctrine.orm.entity_manager');
            // Use $em to interact with the database.
        }
    }
    
    Note: Override setContainer() if needed (see Gotchas).

5. Handling Binary Data

  • Binary Messages: Use Message with binary payloads:
    $client->send(new Message($binaryData, Message::BINARY));
    
  • Base64 Encoding: Encode binary data for JSON APIs if needed.

Gotchas and Tips

1. Archived Package Risks

  • No Long-Term Support: Last release in 2016; may break with newer Symfony/Laravel versions.
    • Mitigation: Fork the repo and update dependencies (e.g., Ratchet, Symfony components).
  • Security: No built-in WSS (secure WebSocket) support. Use a reverse proxy (e.g., Nginx) for HTTPS.

2. Debugging

  • Logs: Enable Symfony logging to debug WebSocket events:
    use Psr\Log\LoggerInterface;
    
    class DemoWebsocket extends Websocket
    {
        private $logger;
    
        public function __construct(LoggerInterface $logger)
        {
            $this->logger = $logger;
        }
    
        public function onMessage(Client $client, Message $message)
        {
            $this->logger->info('Message received', ['payload' => $message->getPayload()]);
        }
    }
    
  • Client-Side Errors: Use browser dev tools (Console > WebSocket tab) to inspect messages/errors.

3. Configuration Quirks

  • Container Injection: If DI fails, manually set the container:
    $websocket = new DemoWebsocket();
    $websocket->setContainer($this->container); // In a service or command.
    
  • Route Conflicts: Ensure WebSocket routes don’t clash with HTTP routes (prefix with /ws/).

4. Performance

  • Memory Leaks: Active clients are stored in memory. Implement a cleanup mechanism:
    public function onClose(Client $client)
    {
        unset(self::$clients[$client->getId()]);
    }
    
  • Scalability: For high traffic, consider:
    • Load balancing (e.g., multiple WebSocket servers behind a proxy).
    • Offloading message processing to a queue (e.g., Redis).

5. Extension Points

  • Custom Protocols: Extend Websocket to add protocol-specific logic.
  • Middleware: Intercept messages/clients by overriding methods (e.g., onMessage).
  • Event Dispatching: Integrate with Symfony’s event system:
    use Symfony\Component\EventDispatcher\EventDispatcherInterface;
    
    class DemoWebsocket extends Websocket
    {
        private $dispatcher;
    
        public function __construct(EventDispatcherInterface $dispatcher)
        {
            $this->dispatcher = $dispatcher;
        }
    
        public function onMessage(Client $client, Message $message)
        {
            $event = new WebsocketEvent($client, $message);
            $this->dispatcher->dispatch($event, 'websocket.message');
        }
    }
    

6. Testing

  • Unit Tests: Mock Client and Message classes to test logic.
  • Integration Tests: Use a WebSocket testing library (e.g., PHP WebSocket Client) to simulate connections:
    $client = new \WebSocket\Client('ws://localhost/ws/demo');
    $client->send('test');
    $response = $client->receive();
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views