MQTT know if a client is subscribed

2019-09-05 11:19发布

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.

标签: java mqtt paho
1条回答
姐就是有狂的资本
2楼-- · 2019-09-05 12:17

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 to lock/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 and client-2 both want to subscribe to foo/bar, they would both need to first subscribe to lock/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 by client-2 and then they both subscribe to foo/bar.

查看更多
登录 后发表回答