Reputation: 704
I'm facing a problem with a real time app that i'm developing. My problem is about user's status using Pusher. I would like to get the correct way to detect when a user leaves the page or keep unactive for a while to set it's status to 'offline', for example. How could I achieve that? I'm almost sure that is not recommended develop this feature at client-side, it should be at server-side, but how? How can I ask to clients if they are still there? Should I create a command and run it wit cron? Are there any mechanism to let the server 'detect' the socket disconnection? Any help will be appreciated, Thx!
Update
With NoseJS and SocketIO it's really simple, you just have to write:
io.on('connection', function (socket) { // When client connects
socket.on('disconnect', function() { // Listen to disconnections from SERVER-SIDE
// Logic when a user disconnects. This is what I want!
});
});
But in Laravel, I only have this:
// A Laravel Event Class that implements the shouldBroadcast interface...
public function broadcastOn()
{
// I think here is where connections happen, but I don't know how to detect 'disconnections' :(
return new PresenceChannel('someString');
}
PD: I'm using Laravel Echo and Pusher :)
Upvotes: 2
Views: 5362
Reputation: 1461
Simplest way is to subscribe to the the ConnectionClosed
event
Providers/EventServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use BeyondCode\LaravelWebSockets\Events\ConnectionClosed;
use App\Listeners\OnConnectionClosed;
class EventServiceProvider extends ServiceProvider
{
protected $listen = [
ConnectionClosed::class => [
OnConnectionClosed::class
]
];
public function boot()
{
parent::boot();
}
}
Listeners/OnConnectionClosed.php
<?php
namespace App\Listeners;
use BeyondCode\LaravelWebSockets\Events\ConnectionClosed;
class OnConnectionClosed
{
public function handle(ConnectionClosed $connection)
{
if( !is_null($connection->appId) && !is_null($connection->socketId) ){
error_log($connection->appId);
error_log($connection->socketId);
}
}
}
Upvotes: 1
Reputation: 2643
You can use presence channels to achieve this. You can then use presence webhooks to notify your server whenever a user enters or leaves the channel.
Upvotes: 6