tabuna / web-socket

Laravel library for asynchronously serving WebSockets.
MIT License
219 stars 29 forks source link

How to define new event #23

Open parsa25eng opened 6 years ago

parsa25eng commented 6 years ago

How to define new event BaseSocketListener subclass and trigger this event ?

tabuna commented 6 years ago

Initiate what? It just allows data exchange. If you want the server to give some information and initiate the messages, then just send it. For this you can use Pawl

parsa25eng commented 6 years ago

As I expect, I should be able to link this data exchange framework to Events of Laravel system. In other words, with binding EventListener to the message exchange system I should be able to exchange desired messages with my clients at desired times. Is it true?

tabuna commented 6 years ago

Yes. I'm using a queue, but it works on normal events too

namespace App\Listeners;

use App\Events\OrderShipped;
use SocketClient;

class SendShipmentNotification
{
    /**
     * Handle the event.
     *
     * @param  \App\Events\OrderShipped  $event
     * @return void
     */
    public function handle(OrderShipped $event)
    {
        SocketClient::send('soket-route',[
                'user_id' =>  $event->order->user_id,
                'message' => 'Thank you for ordering from us.... bla bla bla...',
        ]);
    }
}

and

namespace App\Facades;

use Ratchet\Client;

class SocketClient
{
    /**
     * Get the registered name of the component.
     *
     * @param string $route
     * @param array  $arg
     */
    public static function send($route, array $arg)
    {
        $config = config('socket');
        Client\connect('ws://' . $config['httpHost'] . ':' . $config['port'] . '/' . $route)->then(function ($conn) use (
            $arg
        ) {
            $conn->send(json_encode($arg));
            $conn->close();
        });
    }
}

This all works, but you need to determine for yourself how and to whom you will send