8
votes

Currently I have an MQTT system where one client publishes, and one subscribes. Now I want a system where many clients publish. The susbcriber must understand which client is sending information.

While one obvious way to do this is to simply append a client ID in the publishing message, I wanted to know if there is a way of getting client ID without explicitly adding it to the message.

To elaborate, suppose the topic is "/hello/world", and client 1 publshes "OK", client 2 publishes "ERR". Is there a way to determine which client sent what message?

2

2 Answers

14
votes

I don't believe you can tell who has sent the message without watching the log.

The ways I have overcome this in the past is to either publish the messages with the client id in the topic; (client_id could be anywhere in the topic)

/hello/clientid1/world ok /hello/clientid2/world err /hello/clientid3/world warning

Then subscribe to the topic like this; /hello/+/world Then in your code transform the topic name to get the message and client id.

The other approach I use is to use json in the payload, for example

/hello/world {"msg":"err", "client":"clientid1"}

14
votes

There's no way to do this without either putting the name of the client in the topic, or in the message body itself. This is a simple publish and subscribe system and the principle is that the publishers and subscribers should not need to know about each other - in fact the publisher should not assume that there are any subscribers at all, which is a perfectly possible scenario.

So, if you really need to do this, you need to put the client id in the topic name somehow, or include it inside the body of the published message data.