WebSockets

Yabasi provides real-time communication capabilities through WebSockets using the Ratchet WebSocket server. This enables you to build real-time features like chat applications, live notifications, and real-time dashboards.

Creating a WebSocket Server

Create a WebSocket server by extending the BaseWebSocketServer class:

NotificationServer.php
namespace App\WebSocket;

use Ratchet\ConnectionInterface;
use Yabasi\WebSocket\BaseWebSocketServer;

class NotificationServer extends BaseWebSocketServer
{
    public function onMessage(ConnectionInterface $from, $msg)
    {
        $data = json_decode($msg, true);

        // Broadcast message to all connected clients
        foreach ($this->clients as $client) {
            $client->send(json_encode([
                'type' => 'notification',
                'data' => $data
            ]));
        }
    }
}

Running the WebSocket Server

Run your WebSocket server using the command line:

php yabasi websocket:serve

Client-Side Connection

Connect to your WebSocket server from the client side:

script.js
const socket = new WebSocket('ws://localhost:8080');

socket.onopen = function() {
    console.log('Connected to WebSocket server');
};

socket.onmessage = function(event) {
    const data = JSON.parse(event.data);

    if (data.type === 'notification') {
        console.log('New notification:', data.data);
    }
};

Handling Events

The BaseWebSocketServer provides several events you can handle:

class GameServer extends BaseWebSocketServer
{
    public function onOpen(ConnectionInterface $conn)
    {
        // New connection established
        parent::onOpen($conn);
    }

    public function onClose(ConnectionInterface $conn)
    {
        // Connection closed
        parent::onClose($conn);
    }

    public function onError(ConnectionInterface $conn, \Exception $e)
    {
        // Handle error
        parent::onError($conn, $e);
    }
}

Broadcasting Messages

Send messages to specific clients or broadcast to all connected clients:

// Broadcast to all clients except sender
foreach ($this->clients as $client) {
    if ($from !== $client) {
        $client->send($msg);
    }
}

// Send to specific client
$targetClient->send(json_encode([
    'type' => 'private',
    'message' => 'Private message'
]));

Find the documentation helpful?

Show your support by starring our project on GitHub

Star on GitHub