The question is already posted, Mqtt How a client can get to know that another client is connected or not and How to Find Connected MQTT Client Details
In my case, if client X is already subscribed in a channel A, client Y can't subcribe to the channel A, until X unsubcribes. I can only have one client subscribed in the channel
Can I also use the idea of retained messages and LWT?
If yes, I don't know exactly from where should I start. It would be good to start with a simple example to see how the retained messages and LWT work. So far, I just have experience in publishing and subscribing but no more.
Could you please, tell me some advises may be some links or examples or any useful information so I can have a starting point.
MQTT is all about having multiple clients subscribing to the same topics, it's part of the whole pub/sub pattern and sharing information. So there is nothing baked into the protocol that will do what you want.
You may be able to implement something like the following:
If have a topic say
foo/bar
and you only want one subscriber you could publish a retained message with a payload of the client-id of the subscriber tolock/foo/bar
. You could then publish a "free" to this lock topic when you disconnected and set up a LWT to do the same in case the client dies.The problem with this is that everything is asynchronous so it opens up lots of timing windows for race conditions. e.g. say
client-1
andclient-2
both want to subscribe tofoo/bar
, they would both need to first subscribe tolock/foo/bar
to check it's state. They both do this at very nearly the same time, they then have to wait for some time to see what message they get back ("free" or a client-id). They would both get "free" so would both assume that they can publish their client-ids.client-1
published first shortly followed byclient-2
and then they both subscribe tofoo/bar
.