Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implementation of onSubscribe, onUnsubscribe, onPublish function. #985

Open
kpebron opened this issue Nov 14, 2022 · 0 comments
Open

Implementation of onSubscribe, onUnsubscribe, onPublish function. #985

kpebron opened this issue Nov 14, 2022 · 0 comments

Comments

@kpebron
Copy link

kpebron commented Nov 14, 2022

I would like to ask how to implement the three function from the title. I tried reading the documents but not really getting it. below is my implementation with laravel 8.

<?php

namespace App\WebSockets\SocketHandler;

use App\Websockets\SocketHandler\ChatMessageEventHandler;
use Ratchet\ConnectionInterface;
use Ratchet\RFC6455\Messaging\MessageInterface;
use Ratchet\Wamp\WampServerInterface;
use Ratchet\WebSocket\MessageComponentInterface;


class WebSocketHandler implements MessageComponentInterface, WampServerInterface
{
    function onOpen(ConnectionInterface $conn)
    {
    }

    function onClose(ConnectionInterface $conn)
    {
    }

    function onError(ConnectionInterface $conn, \Exception $e)
    {
    }

    function onMessage(ConnectionInterface $conn, MessageInterface $msg)
    {
    }

    public function onPublish(ConnectionInterface $conn, $topic, $event, array $exclude, array $eligible)
    {
    }

    public function onCall(ConnectionInterface $conn, $id, $topic, array $params)
    {
    }

    public function onSubscribe(ConnectionInterface $conn, $topic)
    {
    }

    public function onUnSubscribe(ConnectionInterface $conn, $topic)
    {
    }
}
<?php

namespace App\Console\Commands;

use App\WebSockets\SocketHandler\WebSocketHandler;
use Illuminate\Console\Command;
use Ratchet\Http\HttpServer;
use Ratchet\Http\OriginCheck;
use Ratchet\Http\Router;
use Ratchet\Server\IoServer;
use Ratchet\WebSocket\WsServer;
use React\EventLoop\Loop;
use React\Socket\SocketServer;
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

class WebSocketServer extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'websockets:serve';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Initializing Websocket server to receive and manage connections';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        $port = 6001;
        echo "Ratchet server started on 127.0.0.1:{$port} \n";
        $address = '0.0.0.0'; // Client address to accept. (0.0.0.0 means receive connections from any)
        $loop = Loop::get();
        $socket = new SocketServer("{$address}:{$port}", [], $loop);
        $routes = new RouteCollection();

        echo "App ws websocket running on 127.0.0.1:{$port}/ws/chat \n";
        $customWebsocketOneServer = new WsServer(new WebSocketHandler());
        $customWebsocketOneServer->enableKeepAlive($loop); // Enable message ping:pong
        $routes->add('ws', new Route('/ws/chat', [
            '_controller' => $customWebsocketOneServer,
        ]));

        $urlMatcher = new UrlMatcher($routes, new RequestContext());
        $router = new Router($urlMatcher);
        $originCheck = new OriginCheck($router, ['127.0.0.1']);
        $socket = new IoServer(new HttpServer($router), $socket, $loop); // Pass $originCheck to filter origin
        $socket->run();
    }
}

Javascript

const socket = new WebSocket(`wss://${window.location.hostname}/ws/chat`);
socket.onopen = function (event) {
    // console.log("on open", event);
};

socket.onmessage = function (event) {
    event = JSON.parse(event.data);
    console.log("websocket message", event);
};

socket.onclose = function (event) {
    // console.log("on close", event);
};

socket.send(
    JSON.stringify({
        access_token: access_token,
        payload: {
            type: "get-users",
        },
    })
);

With this setup, I can send and receive message from client to server using the send and onmessage function in javascript. How should I make my users use/trigger subscribe and unsubscribe function? publish? There are no tutorials found on the internet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant