最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Track the connection status from the backend? - Stack Overflow

programmeradmin3浏览0评论

I am Working on a Chat Application developed By laravel (Laravel Reverb) and reactjs.

Two Projects are developed separately and also i am configuring with Laravel Passport.

The Backend basically serve the Api and Chat server where the frontend configuring the chat server and implementing Apis.

For Tracking User Activity (Online or Offline Status) I am Configuring Presence Channel.

Previously, my task was, when a user connected to the channel A User History Saved on Redis. Which Perfectly Work without any issue.

Now I am trying to configure user disconnected system. When a user is disconnected from the channel it will remove that user history from Redis.

Now Every where i am founding calling a api from frontend so that it can remove that entity.

But I need to Determine the user disconnection from Backend cause When connection stablish i can see Connection stablish message on debug panel and also connection closed message inside debug console.

So I think i can track the connection and disconnection from the server side rather than implementing something on frontend.

So is there a way to track the connection status from the backend side? I can't Handel The Laravel Reverb Disconnect When Tab is closed

I am giving you the whole code. So that any one can understand what is doing and what to do next.

<?php

namespace App\Listeners;

use App\Events\UserStatus;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class UserStatusListener
{
    /**
     * Create the event listener.
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     */
    public function handle(UserStatus $event): void
    {
        $user_id = $event->user_id;
        $status = $event->status;

        Log::info("User Status Changed: User ID {$user_id} is now {$status}");

        if ($status === "connected") {
            // Store user as online in Redis
            Redis::setex("user:online:{$user_id}", 300, json_encode([
                'user_id' => $user_id,
                'status' => 'online',
                'last_seen' => now()->toDateTimeString(),
            ]));
        } elseif ($status === "disconnected") {
            // Remove user from Redis (user disconnected)
            Redis::del("user:online:{$user_id}");
        }
    }
}

This is my UserStatusListner Where I am determining the User Connected status and store this inside Redis.

<?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\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;


class UserStatus implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    
    public $user_id;
    public $status;

    /**
     * Create a new event instance.
     */
    public function __construct($user_id, $status)
    {
        $this->user_id = $user_id;
        $this->status = $status;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return array<int, \Illuminate\Broadcasting\Channel>
     */
    public function broadcastOn()
    {
        return new PresenceChannel('presence-user-status-'.$this->user_id);
    }

    public function broadcastAs()
    {
        return 'user.status'; // Custom event name
    }
}

This is my UserStatus Event Where i called when a Presence Channel is successfully connected.

Broadcast::channel('presence-user-status-{user_id}', function ($user, $user_id) {
    // Check the authenticated user from multiple guards
    $staffUser = Auth::guard('staff_users')->user();
    $businessUser = Auth::guard('business_users')->user();
    $normalUser = Auth::guard('users')->user();

    $userData = [];
    if ($normalUser && (int) $normalUser->user_id === (int) $user_id) {
        $userData = [
            'user_id' => $normalUser->user_id,
            'type' => "user"
        ];

    }

    if ($businessUser && (int) $businessUser->user_id === (int) $user_id) {
        $userData = [
            'user_id' => $businessUser->user_id,
            'type' => "business"
        ];
    }

    if ($staffUser && (int) $staffUser->staff_id === (int) $user_id) {
        $userData = [
            'user_id' => $staffUser->staff_id,
            'type' => "staff"
        ];
        
    }

    if (!empty($userData)) {
        Redis::setex("user:online:{$user_id}", 300, json_encode([
            'user_id' => $userData['user_id'],
            'type' => $userData['type'],
            'last_seen' => now()->toDateTimeString(),
        ]));
        
        // Fire the UserStatus event for tracking
        event(new UserStatus($userData['user_id'], 'connected'));
        return $userData;
    }

    return false; 
});

This is my channel Code of the Presence Channel inside routes/channels

Here When user is online i can store the data into Redis but when a user is disconnect i can't track that. Anyone have any advise or any way to resolve this issue?

N.B - I am Using Laravel 10 Version.

发布评论

评论列表(0)

  1. 暂无评论