Laravel echo, socket io and redis with example : Laravel socket io with redis

Blogs ❯❯ Laravel

Image could not load

Laravel socket io

इस Blog में Laravel में echo , soecket io को redis के साथ implement करेंगे।

Requirements

  • Laravel framework 5.6 or higher

  • laravel events

  • laravel-echo-server

  • socket io

Laravel Sockets and Broadcasting

Laravel में आप broadcasting भी implement कर सकते हैं , means किसी particular place से किसी event को emit करके एक या एक से ज्यादा places पर use listen कर सकते हैं।

इन events को socket की help से trigger और listen किया जाता है।

Setup

सबसे पहले एक fresh laravel project को composer की help से install कर लेते हैं -

composer create-project laravel/laravel chattest --prefer-dist

Installing dependencies

npm install
npm install laravel-echo
npm install socket.io-client

Install php redis

composer require predis/predis

अगर आप windows operating system पर हैं तो , आपको redis app install करना पड़ेगा और उसे port 6379 पर set करना है। और अगर mac / linux है तो आपको command line के through install करना है।

इसके बाद आपको php.ini file में extension=redis check करना है , अगर नहीं है तो आपको php_redis.dll file को download करके xampp/php/ext या wampp/php/ext directory में रख देनी है फिर php.ini file open करके extension=redis save करना है और server restart कर देना है।

Install laravel echo-server with npm
npm install -g laravel-echo-server

अब .env file open करें और नीचे दी गयी lines को replace / add कर दें।

BROADCAST_DRIVER=redis
CACHE_DRIVER=redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
LARAVEL_ECHO_PORT=6001

Preparing laravel echo server

hardware configuration के बाद आपको laravel echo server का config set करना है जहाँ पर आप define करेंगे कि किस port पर events को listen करेंगे।

configuration के set करने के लिए project की root directory में नीचे दी गयी command run कर दें।

laravel-echo-server init

ऊपर दी गयी command completely finish करने पर root directory में एक laravel-echo-server.json name से file बनेगी जिसमे कुछ इस तरह से configuration होगी।

{ "authHost": "http://localhost", "authEndpoint": "/broadcasting/auth", "clients": [], "database": "redis", "databaseConfig": { "redis": {}, "sqlite": { "databasePath": "/database/laravel-echo-server.sqlite" } }, "devMode": true, "host": null, "port": "6001", "protocol": "http", "socketio": {}, "secureOptions": 67108864, "sslCertPath": "", "sslKeyPath": "", "sslCertChainPath": "", "sslPassphrase": "", "subscribers": { "http": true, "redis": true }, "apiOriginAllow": { "allowCors": false, "allowOrigin": "", "allowMethods": "", "allowHeaders": "" } }

यह वही port number लिया गया है जो हमने .env file में LARAVEL_ECHO_PORT में लिया था , अगर आप दूसरे port पर run करना चाहते हैं तो change कर सकते है।

Laravel Generating event

अब एक event generate कर लेते हैं , event generate करने के लिए नीचे दी गयी command run करें -

php artisan make:event TestEvent

ये command run करते ही app/Events directory में TestEvent.php file create होगी उसे open करें और नीचे दिया गया content रख दें।

<?php namespace App\Events; use Illuminate\Broadcasting\Channel; use Illuminate\Queue\SerializesModels; use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Broadcasting\PresenceChannel; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow; class TestEvent implements ShouldBroadcastNow { use Dispatchable, InteractsWithSockets, SerializesModels; public $data = []; /** * Create a new event instance. * * @return void */ public function __construct($data = []) { $this->data = $data; } /** * Get the channels the event should broadcast on. * * @return \Illuminate\Broadcasting\Channel|array */ public function broadcastOn() { return new Channel('TestEvent'); } }

Actually इस file में हम event name और event channel name define करते हैं , by default class name ही event name होते है। और $data में आपको वो data मिल जायगा जो event fire करने पर आप pass करेंगे।

Laravel Fire event

event को आप कही भी fire कर सकते हैं बस आपको उस event class को add करना पड़ेगा और broadcast() method की help से आप event को fire कर पाएंगे। अभी मै web.php में ही event को fire कर रहा हूँ।

<?php use Illuminate\Support\Facades\Route; use App\Events\TestEvent; Route::get('fire-event', function() { broadcast(new TestEvent(["message" => "this is data passing to the event"])); }); Route::view('listen-event', 'test-view');

अब event को listen करने के किये test-view.blade.php file बना ले और नीचे दिया गया content रख दें।

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Listen Event</title> </head> <body> <script> window.laravel_echo_port='{{env("LARAVEL_ECHO_PORT")}}'; </script> <script src="//{{ Request::getHost() }}:{{env('LARAVEL_ECHO_PORT')}}/socket.io/socket.io.js"></script> <script src="{{ asset('public/js/laravel-echo-setup.js') }}" type="text/javascript"></script> <script type="text/javascript"> try { window.Echo.channel('TestEvent').listen('TestEvent', (data) => { alert("Event is working"); console.log("data", data); }); } catch(e) { console.log("Error while listening"); } </script> </body> </html>

Setup Laravel echo-server

blade file में हमने एक laravel-echo-setup.js file add की है , इसे setup करने के लिए resources/js directory में laravel-echo-setup.js file बना लें और नीचे दिया गया code रखकर save कर दें।

// file : resources/js/laravel-echo-setup.js import Echo from 'laravel-echo'; window.Echo = new Echo({ broadcaster: 'socket.io', host: window.location.hostname + ":" + window.laravel_echo_port, enabledTransports: ['ws', 'wss'], disableStats: true, forceTLS: false, transports: ['websocket', 'polling', 'flashsocket'] });

अब आपके project root directory में webpack.mix.js file को open करें और नीचे दी गयी line को रख दें -

let mix = require('laravel-mix'); .... .... mix.js('resources/js/laravel-echo-setup.js', 'public/js');

इसके बाद project root में command line open करें और npm run dev command run करें -

Testing Event

Finally ये सब configuration करने के बाद command line से नीचे दी गयी command को run करें-

laravel-echo-server start

command run करने के बाद कुछ इस तरह से output दिखेगा -

L A R A V E L  E C H O  S E R V E R

version 1.6.3

⚠ Starting server in DEV mode...

✔  Running at localhost on port 6001
✔  Channels are ready.
✔  Listening for http events...
✔  Listening for redis events...

Server ready!

इसके बाद browser में दो tab open करें , एक से event fire करें और दूसरे में उस event को listen करें।

I Hope , आपको laravel में socket के साथ ये demonstration समझ आया होगा।

Recent Blogs

Loading ...

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook