Installation
composer require babdev/websocket-server
Ensure your server has ext-sockets enabled (required for WebSocket functionality).
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.)
First Use Case: Echo Server Handle incoming messages with a simple callback:
$server->on('message', function ($connection, $data) {
$connection->send($data); // Echo back
});
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'));
});
}
Configuration
Add to config/websocket.php:
return [
'host' => env('WEBSOCKET_HOST', '0.0.0.0'),
'port' => env('WEBSOCKET_PORT', 8080),
'ping_interval' => 30, // Seconds
];
Event-Driven Workflows
$server->on('connect', function ($connection) {
logger()->info('New connection: ' . $connection->getId());
});
$server->on('disconnect', function ($connection) {
logger()->info('Connection closed: ' . $connection->getId());
});
Broadcasting to Clients
Use a ConnectionManager to send messages to all/specific clients:
$server->getConnectionManager()->broadcast('Hello, all!');
$server->on('connect', function ($connection) use ($server) {
if (!$server->authenticate($connection, 'secret-token')) {
$connection->close();
}
});
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);
}
});
Blocking Calls
$server->on('message', function ($connection, $data) {
dispatch(new ProcessWebsocketData($data))->onQueue('websocket');
});
Connection Leaks
disconnect events to clean up:
$server->on('disconnect', function ($connection) {
$connection->getId(); // Log or track for debugging
});
Cross-Origin Issues
$server->on('http_request', function ($request, $response) {
$response->setHeader('Access-Control-Allow-Origin', '*');
});
Port Conflicts
lsof -i :8080 to check.$server->setDebug(true); // Logs to stderr
$connection->getId() and $connection->getRemoteAddress() to track clients.onMessage to log raw data:
$server->on('message', function ($connection, $data) {
logger()->debug('Raw data: ' . bin2hex($data));
});
Custom Protocols
Extend Babdev\WebsocketServer\Protocol\Protocol to support custom framing.
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);
Load Balancing For horizontal scaling, use a reverse proxy (e.g., Nginx) with sticky sessions to route WebSocket connections to the same backend instance.
Laravel Events Bridge WebSocket events to Laravel’s event system:
$server->on('message', function ($connection, $data) {
event(new WebsocketMessageReceived($data));
});
How can I help you explore Laravel packages today?