Velkan Velkan - 1 year ago 112
Node.js Question

How to tunnel browser-side mqtt through the server?

Browser uses this to connect to a mosquitto (websockets mode):

new Paho.MQTT.Client('localhost', 9001, '');

As I understand, it's a direct connection from the browser to the broker. It won't work in the normal setup when the browser is on a different machine.

In normal setup nodejs and the broker are on the same machine. How to route that via nodejs, so nodejs could forward the connections to the
? And I don't want to write a lot of code for repacking messages and reimplementing different subscription API.

Answer Source

localhost is a special case hostname that refers to the machine some code is running on.

Assuming the broker you want to connect to is on the same machine that hosted the webpage you can use the location variable to get the information you need.

var client = new Paho.MQTT.Client(location.hostname, 9001, '');

Assuming you are proxying the webapp then the websockets can be proxied as well on the same port which would end up with:

var client = new Paho.MQTT.Client(location.hostname, parseInt(location.port), '');

To proxy the mqtt as well (using nginx):

location /mqtt {
    proxy_http_version  1.1;
    proxy_set_header    Upgrade $http_upgrade;
    proxy_set_header    Connection "upgrade";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download