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 Server Laravel Package

babdev/websocket-server

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require babdev/websocket-server
    

    Ensure your server has ext-sockets enabled (required for WebSocket functionality).

  2. Basic Server Initialization Create a minimal WebSocket server in a Laravel route or artisan command:

    use Babdev\WebsocketServer\WebsocketServer;
    
    $server = new WebsocketServer('0.0.0.0', 8080);
    $server->run();
    

    Run via CLI:

    php artisan websocket:serve
    

    (Note: For Laravel integration, consider wrapping this in a service provider or console command.)

  3. First Use Case: Echo Server Handle incoming messages with a simple callback:

    $server->on('message', function ($connection, $data) {
        $connection->send($data); // Echo back
    });
    

Implementation Patterns

Laravel Integration

  1. Service Provider Setup Register the WebSocket server as a singleton in AppServiceProvider:

    public function register()
    {
        $this->app->singleton(WebsocketServer::class, function () {
            return new WebsocketServer(config('websocket.host'), config('websocket.port'));
        });
    }
    
  2. Configuration Add to config/websocket.php:

    return [
        'host' => env('WEBSOCKET_HOST', '0.0.0.0'),
        'port' => env('WEBSOCKET_PORT', 8080),
        'ping_interval' => 30, // Seconds
    ];
    
  3. Event-Driven Workflows

    • Connection Handling:
      $server->on('connect', function ($connection) {
          logger()->info('New connection: ' . $connection->getId());
      });
      
    • Disconnection:
      $server->on('disconnect', function ($connection) {
          logger()->info('Connection closed: ' . $connection->getId());
      });
      
  4. Broadcasting to Clients Use a ConnectionManager to send messages to all/specific clients:

    $server->getConnectionManager()->broadcast('Hello, all!');
    

Authentication & Middleware

  • Basic Auth:
    $server->on('connect', function ($connection) use ($server) {
        if (!$server->authenticate($connection, 'secret-token')) {
            $connection->close();
        }
    });
    
  • Custom Middleware: Extend Babdev\WebsocketServer\Middleware\Middleware and bind it:
    $server->addMiddleware(new class implements Middleware {
        public function handle($connection, callable $next) {
            if ($connection->getId() === 'blocked-id') {
                $connection->close();
                return;
            }
            $next($connection);
        }
    });
    

Gotchas and Tips

Pitfalls

  1. Blocking Calls

    • The WebSocket server runs in a blocking loop. Avoid long-running tasks in event handlers (e.g., database queries). Use queues or async processing instead.
    • Workaround: Offload work to Laravel queues:
      $server->on('message', function ($connection, $data) {
          dispatch(new ProcessWebsocketData($data))->onQueue('websocket');
      });
      
  2. Connection Leaks

    • Unclosed connections can exhaust resources. Always handle disconnect events to clean up:
      $server->on('disconnect', function ($connection) {
          $connection->getId(); // Log or track for debugging
      });
      
  3. Cross-Origin Issues

    • By default, the server doesn’t handle CORS. Add headers manually:
      $server->on('http_request', function ($request, $response) {
          $response->setHeader('Access-Control-Allow-Origin', '*');
      });
      
  4. Port Conflicts

    • Ensure the port isn’t already in use (e.g., by Laravel’s built-in server). Use lsof -i :8080 to check.

Debugging Tips

  • Logging: Enable debug mode in the server:
    $server->setDebug(true); // Logs to stderr
    
  • Connection Inspection: Use $connection->getId() and $connection->getRemoteAddress() to track clients.
  • Packet Dumps: Override onMessage to log raw data:
    $server->on('message', function ($connection, $data) {
        logger()->debug('Raw data: ' . bin2hex($data));
    });
    

Extension Points

  1. Custom Protocols Extend Babdev\WebsocketServer\Protocol\Protocol to support custom framing.

  2. SSL/TLS Use Babdev\WebsocketServer\SSL\SSLContext for wss://:

    $sslContext = new SSLContext('/path/to/cert.pem', '/path/to/key.pem');
    $server = new WebsocketServer('0.0.0.0', 8443, null, $sslContext);
    
  3. Load Balancing For horizontal scaling, use a reverse proxy (e.g., Nginx) with sticky sessions to route WebSocket connections to the same backend instance.

  4. Laravel Events Bridge WebSocket events to Laravel’s event system:

    $server->on('message', function ($connection, $data) {
        event(new WebsocketMessageReceived($data));
    });
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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