When I try to connect to Mosquitto server through this JS, I receive this error:
WebSocket connection to 'ws://xx.xxx.xxx.xxx:1883/mqtt' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET
I tried from console and it works fine. I tried with Java client as provider and consumer and it works fine. So I can't undertand what should I do to have it working.
This is JS:
client = new Paho.MQTT.Client("xx.xxx.xxx.xxx", 1883, "clientId");
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
// connect the client
client.connect({onSuccess:onConnect});
This is Java (working):
@Stateless
@LocalBean
public class PahoManager implements MqttCallback {
MqttClient client;
public void init() {
try {
client = new MqttClient("tcp://192.168.50.10:1883", "pahomqttpublish1");
client.connect();
client.subscribe("pahodemo/test");
} catch (MqttException e) {
e.printStackTrace();
}
}
public void doDemo() {
try {
MqttMessage message = new MqttMessage();
message.setPayload("Ciao Pluto".getBytes());
client.publish("pahodemo/test", message);
//client.disconnect();
} catch (MqttException e) {
e.printStackTrace();
}
}
@Override
public void connectionLost(Throwable thrwbl) {
System.out.println("Connection Lost");
}
@Override
public void messageArrived(String string, MqttMessage mm) throws Exception {
System.out.println("Message: " + string + mm);
}
@Override
public void deliveryComplete(IMqttDeliveryToken imdt) {
System.out.println("Message delivered");
}
}
As hardillb said, mosquitto does not yet support websockets. If you want native websockets, there are other solutions like HiveMQ. You can see a full list of brokers with websocket support here (you may need to scroll the table to the right). You can learn more about MQTT over websockets in this blog post:
Please make sure, that you are connecting to the websocket port which is usually not 1883. In practice this means, that your TCP MQTT clients connect to port 1883 and your websocket clients to another port like 8000.
The usual disclaimer: I'm one of the HiveMQ developers so this answer may be biased ;-)