raheelrafiq326 / websocket
Websocket support for laravel applications.
v1.0.1
2023-12-01 14:33 UTC
Requires
- cboden/ratchet: ^0.4.4
- textalk/websocket: ^1.5
README
Documentation, Installation, and Usage Instructions
Introduction
This package allows you to add socket server within a package.
Install library in laravel project.
composer require raheelrafiq326/websocket
Documentation
Installation
Publish config and js files in project.
php artisan vendor:publish --tag=websocket
php artisan websocket:serve
After installation add below command in schedule function in app\Console\Kernel.php (if want to add websocket server from cronjob).
protected function schedule(Schedule $schedule): void { // call this command to be schedule $schedule->command('websocket:serve')->withoutOverlapping(); }
After this run scheduler (in development or local).
php artisan schedule:run
Add above command in cron job in server (production).
Usage
you can use below code to broadcast event from controller or any other class.
use RaheelRafiq326\Websocket\WebSocketClient; // Change value with your channel name. $channel = "<Channel Name>"; // Change value with your event name. $event = "<Event Name>"; // Chnage value according to your requirement. $data = [ "message" => "Hi" ]; // Call sendMessage function of WebSocketClient from package. WebSocketClient::sendMessage($channel, $event, $data);
Testing
Run below command if you didn't publish js files.
php artisan vendor:publish --tag=websocket-js
You can test websocket connection using socket.js. Which was exported to public/vendor/websocket directory.
<script src="{{ asset('vendor/websocket/socket.js') }}"></script> <script> // connect websocket const socket = new Socket("{{ config('websocket.host') }}") // check if socket connect successfully socket.onopen((event) => { console.log("onopen event ==> ", event) }) // listen events socket.listen({ channel: "<Channel Name>", event: "<Event Name>", callback: (event) => { console.log("event listen ==> ", event) } }) </script>
License
The MIT License (MIT). Please see License File for more information.