Your original question, nor responses to subsequent questions identify which broker implementation you are using. So there may be a more efficient answer to your question.
Without that information, let's focus on what you can do in the protocol itself.
MQTT supports RETAINED messages. This is where the broker will store the most recent retained message against each topic. When a client subscribes to the topic, it will receive the retained message (if one exists).
There is also the Last Will and Testament (LWT) feature (that goetzchr refers to), that can be used to publish a message on behalf of the client if it abnormally disconnects.
Combining these two features allows you to build a simple presence service on the broker, all within the protocol. It works like this:
when a client connects, it publishes a RETAINED message to a topic unique to it, for example:
clients/my_client_id/state
with a payload of 1
. (substituting my_client_id
with the client's own id.
it also, on connect, sets a LWT message to be published to the same topic, but with a payload of 0
. This should also be a RETAINED message.
when a client disconnects cleanly, it publishes a RETAINED message to the same topic with a payload of 0
This allows another client to subscribe to clients/#
to receive all the messages indicating the changes in clients' connection state (the full topic identifying the client, and the value of the payload indicating the connection state).
To obtain more information than just connected state, the clients can publish another retained message on connect, to another topic, eg clients/my_client_id/info
that contains all of the information you're interested in.
This only works if you have control of all the clients that are connecting to your broker and able to get them to behave like this.
This is not an ideal approach; hopefully your broker implementation will provide some server-side means of doing this.