Home > Blockchain >  Can a webapp connect to mosquitto?
Can a webapp connect to mosquitto?

Time:06-29

I have a mosquitto_sub running on background on serverA, let's say with topic "TEST", port 1883. I followed this to use nginx as a stream proxy to mosquitto, on ServerB.

Testing the setup sending a message to ServerB, using mosquitto_pub, the message is received and displayed correctly on serverA.

Now I'd like that a webapp running on serverC could receive the mqtt messages I send using a websocket, as far as I understand that nginx setup is made exactly for this purpose because browser can't use directly mqtt protocol.

I did two tests:

  • pointing the websocket to ServerB stream (wss://serverB:1883)
  • pointing the websocket to nginx reverse proxy with this config:

.

...
server {
    listen 443 ssl;
    ...

    location /webapp/websocket {
            proxy_set_header HOST $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_pass_request_headers on;
            proxy_pass http://serverB:1883/;
            proxy_http_version 1.0;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "Upgrade";
            proxy_read_timeout 1800s;
    }

}

With both the websocket doesn't work, with error 502 Bad Gateway. My questions are, did I understand wrong and can it be done? Does it say error 502 just because the webapp must be programmed to specify the topic to listen?

CodePudding user response:

The Mosquitto broker supports MQTT over WebSockets, but it has to be on a separate port to native MQTT over TCP.

So if Mosquitto is normally listening on port 1883, you need to pick a different port to run the MQTT over WebSockets listener. e.g.

listener 1883

listener 8083
protocol websockets

You would then need to update the port in the proxy_pass entry to match.

  • Related