mochi-mqtt / server

The fully compliant, embeddable high-performance Go MQTT v5 server for IoT, smarthome, and pubsub

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

mqtt.js connecting issue

alexmengyuan opened this issue · comments

I am running a mochi websocket server behind traefik reverse proxy,
in browser I am testing it with mqtt.js
the issue I met is that the connection just give 400,
and server log shows nothing,
when I use postman with ws related headers the server log shows unexpected EOF,
how should I approach the issue?
thanks

or does mqtt.js directly working with the websocket listener? does it need any additional configuration?

commented

I think you should first check if it's a compatibility issue between mochi-mqtt and mqtt.js, or if there's a problem with your reverse proxy. As far as I know, MQTTX supports WebSocket connections to the broker server. You can try using MQTTX to connect to your broker in your environment. If MQTTX also encounters the same issue, then you can try connecting to the broker separately without using the proxy. See if the problem persists when connecting directly to the broker without the proxy. If there are no issues when not using the proxy, then you need to investigate the cause related to the proxy. I hope this helps.

Hi,
I tested locally, using mqttx as client and mochi mqtt as server, the error remain same for me,


import (
	"log"
	"os"
	"os/signal"
	"syscall"

	mqtt "github.com/mochi-mqtt/server/v2"
	"github.com/mochi-mqtt/server/v2/hooks/auth"
	"github.com/mochi-mqtt/server/v2/hooks/debug"
	"github.com/mochi-mqtt/server/v2/listeners"
	"github.com/rs/zerolog"
)

func main() {

	sigs := make(chan os.Signal, 1)
	done := make(chan bool, 1)
	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
	go func() {
		<-sigs
		done <- true
	}()

	server := mqtt.New(nil)
	l := server.Log.Level(zerolog.DebugLevel)
	server.Log = &l

	_ = server.AddHook(new(debug.Hook), &debug.Options{
		ShowPacketData: true,
	})
	_ = server.AddHook(new(auth.AllowHook), nil)

	ws := listeners.NewWebsocket("ws1", ":1882", nil)
	err := server.AddListener(ws)
	if err != nil {
		log.Fatal(err)
	}

	go func() {
		err := server.Serve()
		if err != nil {
			log.Fatal(err)
		}
	}()

	<-done
	server.Log.Warn().Msg("caught signal, stopping...")
	server.Close()
	server.Log.Info().Msg("main.go finished")
}

the mochi mqtt server code is like above, pretty much like copied from example,
I build and run it within wsl of windows environment, the server started normally with logs,
then in browser localhost:1882 gives bad request, I guess it means windows -> wsl is ok,
then within MQTTX ui, I tried ws://localhost:1882 and for the path part I tried to enter nothing but end up with a space,
in this case it gives bad request as well,
does anybody tested with mqtt.js before? is there working example by any chance?
thanks

commented

I took some time to write this demo, and you can take a look. The result of my tests shows that mqtt.js can connect to Mochi without any issues. It's possible that there might be a problem between your WSL and Windows. In my environment, the Mochi broker is running on Windows, and this demo is also running in a web browser on the same computer. I copied and used the code you provided in your previous messages in the "cmd/main.go" file. Below is the client-side demo code:

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <input id="_message" width="300px" height="200px">
    <button id="_sendBtn">Send Message</button>
    <div id="div1"></div>
    <div id="div2"></div>
    <div id="div3"></div>
</body>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
<script type="text/javascript">
    $(function () {
        const options = {
            clean: true,
            connectTimeout: 4000,
            clientId: 'client_id',
        }
        const connectUrl = 'ws://localhost:1882/'
        const client = mqtt.connect(connectUrl, options);

        // Callback triggered when reconnecting starts
        client.on('reconnect', () => {
            $("#div1").text("Reconnecting.....");
        });

        // Callback triggered when the connection is closed
        client.on("close", function () {
            $("#div1").text("Client has disconnected.....");
        });

        // MQTT 5.0 feature: Callback triggered when a disconnect packet is received from the broker
        client.on("disconnect", function (packet) {
            console.log("Received a disconnect packet from the broker....." + packet);
        });

        // Callback triggered when the client goes offline
        client.on("offline", function () {
            $("#div1").text("Client is offline.....");
        });

        // Callback triggered when the client encounters an error
        client.on("error", (error) => {
            $("#div1").text("Client encountered an error....." + error);
        });

        // Callback triggered when any data packet is sent by the client. This includes published() packets and MQTT packets used for managing subscriptions and connections.
        client.on("packetsend", (packet) => {
            console.log("Client sent a data packet....." + packet.payload);
        });

        // Callback triggered when any data packet is received by the client. This includes information packets from subscribed topics and MQTT packets used for managing subscriptions and connections.
        client.on("packetreceive", (packet) => {
            console.log(packet);
        });

        // Callback triggered after successful connection
        client.on("connect", function (connack) {
            $("#div1").text("Successfully connected to the server" + new Date());
            /**
             * Subscribe to a topic
             * client.subscribe(topic/topic array/topic object, [options], [callback])
             * topic: a string type topic or an array of topics, can also be an object
             * options
             */
            client.subscribe("/test_topic", { qos: 0 });

        });

        $("#_sendBtn").on('click', function () {
            // Publish data
            var message = $("#_message").val();
            if (message == '') {
                alert("Please enter the message to send");
                return;
            }

            client.publish("/test_topic", message, { qos: 2 });
            $("#div2").text("Sent successfully");
            $("#_message").val("");
        })

        // Callback triggered when the client receives a published message
        /**
         * topic: topic of the received data packet
         * message: payload of the received data packet
         * packet: the received data packet
         */
        client.on('message', (topic, message, packet) => {
            $("#div3").text("Client received a subscribed message, topic=" + topic + "; Message data:" + message + "; Data packet:" + packet);
        });

        // Automatically disconnect the client when the page is closed
        $(window).bind("beforeunload", () => {
            $("#div1").text("Client window closed, disconnecting");
            client.disconnect();
        })
    });
</script>

</html>
commented

@alexmengyuan Has this issue been resolved? Can we close this issue now?

thank you for the help, my problem solved now, it turn out to be a traifik proxy auth issue as suspected..