Last active
April 26, 2023 10:32
-
-
Save abdellatif-laghjaj/3f90ba2d2ad4b502ae11dacfff85d6a2 to your computer and use it in GitHub Desktop.
Setup laravel websockets with flutter: Listen to event from flutter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
return [ | |
/* | |
|-------------------------------------------------------------------------- | |
| Default Broadcaster | |
|-------------------------------------------------------------------------- | |
| | |
| This option controls the default broadcaster that will be used by the | |
| framework when an event needs to be broadcast. You may set this to | |
| any of the connections defined in the "connections" array below. | |
| | |
| Supported: "pusher", "ably", "redis", "log", "null" | |
| | |
*/ | |
'default' => env('BROADCAST_DRIVER', 'null'), | |
/* | |
|-------------------------------------------------------------------------- | |
| Broadcast Connections | |
|-------------------------------------------------------------------------- | |
| | |
| Here you may define all of the broadcast connections that will be used | |
| to broadcast events to other systems or over websockets. Samples of | |
| each available type of connection are provided inside this array. | |
| | |
*/ | |
'connections' => [ | |
'pusher' => [ | |
'driver' => 'pusher',//we just use pusher api not pusher | |
'key' => env('PUSHER_APP_KEY'), | |
'secret' => env('PUSHER_APP_SECRET'), | |
'app_id' => env('PUSHER_APP_ID'), | |
'options' => [ | |
'cluster' => env('PUSHER_APP_CLUSTER'), | |
'useTLS' => false, | |
'host' => '127.0.0.1', | |
'port' => 6001,//port that we will use | |
'scheme' => 'http',//https if we use ssl | |
], | |
], | |
'ably' => [ | |
'driver' => 'ably', | |
'key' => env('ABLY_KEY'), | |
], | |
'redis' => [ | |
'driver' => 'redis', | |
'connection' => 'default', | |
], | |
'log' => [ | |
'driver' => 'log', | |
], | |
'null' => [ | |
'driver' => 'null', | |
], | |
], | |
]; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Events; | |
use Illuminate\Broadcasting\Channel; | |
use Illuminate\Broadcasting\InteractsWithSockets; | |
use Illuminate\Broadcasting\PresenceChannel; | |
use Illuminate\Broadcasting\PrivateChannel; | |
use Illuminate\Contracts\Broadcasting\ShouldBroadcast; | |
use Illuminate\Foundation\Events\Dispatchable; | |
use Illuminate\Queue\SerializesModels; | |
class HelloEvent implements ShouldBroadcast | |
{ | |
use Dispatchable, InteractsWithSockets, SerializesModels; | |
/** | |
* Create a new event instance. | |
* | |
* @return void | |
*/ | |
public $message; | |
public function __construct($message) | |
{ | |
$this->message = $message; | |
} | |
/** | |
* Get the channels the event should broadcast on. | |
* | |
* @return \Illuminate\Broadcasting\Channel|array | |
*/ | |
public function broadcastOn() | |
{ | |
return new Channel('home'); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:convert'; | |
import 'package:flutter/material.dart'; | |
import 'package:get/get.dart'; | |
import 'package:web_socket_channel/io.dart'; | |
void main() { | |
runApp(MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter WebSocket Demo', | |
home: MyHomePage(), | |
); | |
} | |
} | |
class MyHomePage extends StatefulWidget { | |
@override | |
_MyHomePageState createState() => _MyHomePageState(); | |
} | |
class _MyHomePageState extends State<MyHomePage> { | |
final channel = | |
IOWebSocketChannel.connect('ws://localhost:6001/app/websocketkey'); | |
var message = ''; | |
@override | |
void initState() { | |
super.initState(); | |
channel.sink.add(json.encode({ | |
"event": "pusher:subscribe", | |
"data": {"channel": "home"} | |
})); | |
channel.stream.listen((data) { | |
var jsonData = json.decode(data); | |
var eventData = jsonData['data']; | |
if (eventData != null) { | |
var newMessage = json.decode(eventData)['message']; | |
if (newMessage != null) { | |
setState(() { | |
message = newMessage; | |
}); | |
showDialog( | |
context: context, | |
builder: (context) { | |
return AlertDialog( | |
content: Text(message), | |
); | |
}, | |
); | |
} | |
} | |
}, onError: (error) { | |
print("Socket: error => $error"); | |
}, onDone: () { | |
print("Socket: done"); | |
}); | |
} | |
@override | |
void dispose() { | |
channel.sink.close(); | |
super.dispose(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar(title: Text('Flutter WebSocket Demo')), | |
body: Center( | |
child: Text(message), | |
), | |
); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
web_socket_channel: ^2.4.0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//test websocket | |
Route::get('/test', function () { | |
event(new \App\Events\HelloEvent('hello from laravel')); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
return [ | |
/** | |
* This package comes with multi tenancy out of the box. Here you can | |
* configure the different apps that can use the webSockets server. | |
* | |
* Optionally you can disable client events so clients cannot send | |
* messages through each other via the webSockets. | |
*/ | |
'apps' => [ | |
[ | |
'id' => env('PUSHER_APP_ID'), | |
'name' => env('APP_NAME'), | |
'key' => env('PUSHER_APP_KEY'), | |
'secret' => env('PUSHER_APP_SECRET'), | |
'path' => env('PUSHER_APP_PATH'), | |
'capacity' => null, | |
'enable_client_messages' => false,//two client can send message with each other without going to server this is good for typing... | |
'enable_statistics' => true,//if we don't want statistics make this false | |
], | |
], | |
/** | |
* This class is responsible for finding the apps. The default provider | |
* will use the apps defined in this config file. | |
* | |
* You can create a custom provider by implementing the | |
* `appProvier` interface. | |
*/ | |
'app_provider' => BeyondCode\LaravelWebSockets\Apps\ConfigAppProvider::class, | |
/* | |
* This array contains the hosts of which you want to allow incoming requests. | |
* Leave this empty if you want to accepts requests from all hosts. | |
*/ | |
'allowed_origins' => [ | |
// | |
], | |
/* | |
* The maximum request size in kilobytes that is allowed for an incoming WebSocket request. | |
*/ | |
'max_request_size_in_kb' => 250, | |
/* | |
* This path will be used to register the necessary routes for the package. | |
*/ | |
'path' => 'laravel-websockets', | |
/* | |
* Define the optional SSL context for your WebSocket connections. | |
* You can see all available options at: http://php.net/manual/en/context.ssl.php | |
*/ | |
'ssl' => [ | |
/* | |
* Path to local certificate file on filesystem. It must be a PEM encoded file which | |
* contains your certificate and private key. It can optionally contain the | |
* certificate chain of issuers. The private key also may be contained | |
* in a separate file specified by local_pk. | |
*/ | |
'local_cert' => null, | |
/* | |
* Path to local private key file on filesystem in case of separate files for | |
* certificate (local_cert) and private key. | |
*/ | |
'local_pk' => null, | |
/* | |
* Passphrase with which your local_cert file was encoded. | |
*/ | |
'passphrase' => null | |
], | |
'statistics' => [ | |
/* | |
* This model will be used to store the statistics of the WebSocketsServer. | |
* The only requirement is that the model should be or extend | |
* `WebSocketsStatisticsEntry` provided by this package. | |
*/ | |
'model' => \BeyondCode\LaravelWebSockets\Statistics\Models\WebSocketsStatisticsEntry::class, | |
/* | |
* Here you can specify the interval in seconds at which statistics should be logged. | |
*/ | |
'interval_in_seconds' => 60, | |
/* | |
* When the clean-command is executed, all recorded statistics older than | |
* the number of days specified here will be deleted. | |
*/ | |
'delete_statistics_older_than_days' => 60 | |
], | |
]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment