Get a list of connected client IDs from MQTT client

one way to implement this is let the client publish a message with topic "status/client-id" and payload "1" every time when it connects the broker, and with payload "0" when it disconnects.

Then on the server(broker) side, setup another client subscribe to the topic "status/#", when it gets any message like this, store the client-id and payload(connected or not) into database.

then you can read the database to know exactly which client is online or offline.


method I: handle in client logic

as @user1048839 says, use client's LWT & online publish msg, maintain client status on a custom topic. subscript this topic & maintain client list self.

if pub retain msg, once sub will get the client list.

method II: change mosquitto broker code

official code not support online_list,
so I patched mosquitto 1.5.4, add 2 custom sys topic:

1. online list

mosquitto_sub -i DDD -v -t '$SYS/broker/chen_list'
$SYS/broker/chen_list
0 - CLOUD0_19108
1 - EEE
2 - DDD

2. online/offline event

mosquitto_sub -i DDD -v -t '$SYS/broker/chen_state/#'
$SYS/broker/chen_state/DDD 1
$SYS/broker/chen_state/EEE 1
$SYS/broker/chen_state/CLOUD0_19108 1
$SYS/broker/chen_state/EEE 0
$SYS/broker/chen_state/EEE 1

// if pub retain msg, sub this topic can get all clients online state (in payload).

test source code on github:

4-online-list

5-online-event

Tags:

Client

Mqtt