MQTT.js not connecting from websockets - websocket

I'm trying to connect to websocket client of MQTT.js but unable to get a handshake with the server.
My Code :
<html>
<head>
<title>test Ws mqtt.js</title>
</head>
<body>
<script src="//unpkg.com/mqtt#2.5.0/dist/mqtt.min.js"></script>
<script>
var options = {
clientId: 'service-3Kx03pKnM2',
connectTimeout: 5000,
hostname: 'xxx.xxx.xxx',
port: 8000
};
var client = mqtt.connect(options);
client.on('connect', function () {
client.subscribe('presence');
client.publish('presence', 'Hello mqtt')
});
client.on('message', function (topic, message) {
console.log(message.toString());
client.end();
});
</script>
</body>
</html>
I'm getting this error : WebSocket connection to 'ws://broker.hivemq.com:8000/' failed: Connection closed before receiving a handshake response.
Please let me know if I'm doing any mistake.
I'm not using any other scripts other than unpkg.com/mqtt#2.5.0/dist/mqtt.min.js

You are missing the path in your connection options.
The HiveMQ public broker listens on /mqtt for websocket connections, which is in accordance with the Eclipse Wiki
The path portion of the url specified on the MQTT connect should be "mqtt"
For instance ws://m2m.eclipse.org:800/mqtt . mqtt should be the default with the option for an alternative to be configured / specified
You need to add path: '/mqtt' in your options.
var options = {
clientId: 'service-3Kx03pKnM2',
connectTimeout: 5000,
hostname: 'xxx.xxx.xxx',
port: 8000,
path: '/mqtt'
};

Related

failed to connect webpage to MQTT broker using paho-mqtt-javascript

I'm using a mosquitto MQTT broker (ip:192.168.1.61 and port:1883)
here is my HTML code:
<html>
<head>
<title>My First Value</title>
<h1>Main Body</h1>
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.js" type="text/javascript"></script>
</head>
<body>
<h1><div id="connstatus">
Mqtt Not connected.</div></h1>
</body>
<script>
var host = "192.168.1.61";
var port=1883;
var user="Fares";
var pass="1+4=5";
// Create a client instance
client = new Paho.MQTT.Client(host,1883, "clientId");
// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
// connect the client
client.connect({onSuccess:onConnect});
// called when the client connects
function onConnect() {
// Once a connection has been made, make a subscription and send a message.
console.log("onConnect");
client.subscribe("World");
message = new Paho.MQTT.Message("Hello");
message.destinationName = "World";
client.send(message);
}
// called when the client loses its connection
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:"+responseObject.errorMessage);
}
}
// called when a message arrives
function onMessageArrived(message) {
console.log("onMessageArrived:"+message.payloadString);
}
</script>
</html>
here is my .config file:
listener 8883
keyfile /mosquitto/config/certs/broker.key
listener 8083 protocol websockets
keyfile /mosquitto/config/certs/broker.key
require_certificate false
persistence true persistence_location /mosquitto/data/
errors:
console:
WebSocket connection to 'wss://192.168.1.61:1883/mqtt' failed: Error in connection establishment: net::ERR_CONNECTION_RESET
Paho.MQTT.ClientImpl._doConnect # mqttws31.js:977
Paho.MQTT.ClientImpl._disconnected # mqttws31.js:1459
Paho.MQTT.ClientImpl._on_socket_error # mqttws31.js:1347
(anonymous) # mqttws31.js:157
Port 1883 is the default for Native MQTT, not MQTT over WebSockets.
The Paho Javascript driver requires the broker to support and be configured to accept connections from clients using MQTT over WebSockets.
Your mosquitto.conf looks a little screwy (protocol elements should be on their own line), it should look like this:
listener 8883
keyfile /mosquitto/config/certs/broker.key
listener 8083
protocol websockets
keyfile /mosquitto/config/certs/broker.key
require_certificate false
persistence true persistence_location /mosquitto/data/
It appears you have configured the WebSocket listener on port 8083 so your code should be using that not 1883
var host = "192.168.1.61";
var port= 8083;
Also to enable MQTT over TLS and MQTT over Secure Websockets you are going to need to include a certfile entry as well as a keyfile

Connecting socket.io client to https

I'm trying to build a web chat application and want to connect my client to the socket.io server with https.
Seems like everything's fine, but the client is not connecting after all..
Server Code:
var app = require('express')();
var fs = require('fs');
var options = {
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.crt')
};
var server = require('https').createServer(options, app).listen(3000,function(){
console.log("Https server started on port 3000");
});
var io = require('socket.io').listen(server);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log("Client connected");
/*....*/
});
Client code to connect to server:
$(function($){
var socket = io.connect('https://localhost:3000', {secure: true});
.....
});
It kind of doesn't run the code inside of $(function($)..
When I make it a http server it works just fine..
Simply
var socket = io.connect('/', {secure: true});
EDIT: By default socket.io will try to establish a connection on the same host as webserver hosts web content, so no need to specifying host/protocol/port. The / states to connect to default namespace.
I solved the problem..
So for http it was enough if you begin your script on the client with
$(function(){
....
});
But it wouldn't work with https.
I changed it to
jQuery(function($){
....
})(jQuery);
Pretty odd but it worked for me.

WebSocket connection establishment error from browser

I have mosquitto MQTT broker running on my machine. And I want to run the MQTT client from browser. This is what I have done in a Django app:
<html>
<head>
<title>Mosquitto Websockets</title>
{% load staticfiles %}
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="{% static 'js/mqttws31-min.js' %}" type="text/javascript"></script>
<script src="{% static 'js/jquery.min.js' %}" type="text/javascript"></script>
<script src="{% static 'js/config.js' %}" type="text/javasacript"></script>
<script type="text/javascript">
var mqtt;
var reconnectTimeout = 2000;
function MQTTconnect() {
host = '127.0.0.1';
port = 1883;
useTLS = false;
cleansession = true;
username = null;
password = null;
mqtt = new Paho.MQTT.Client(host, port,
"myclientid_" + parseInt(Math.random() * 100, 10));
/*mqtt = new Messaging.Client(
host,
port,
"web_" + parseInt(Math.random() * 100,
10));
*/
var options = {
timeout: 3,
useSSL: useTLS,
cleanSession: cleansession,
onSuccess: onConnect,
onFailure: function (message) {
$('#status').val("Connection failed: " + message.errorMessage + "Retrying");
setTimeout(MQTTconnect, reconnectTimeout);
}
};
mqtt.onConnectionLost = onConnectionLost;
mqtt.onMessageArrived = onMessageArrived;
if (username != null) {
options.userName = username;
options.password = password;
}
console.log("Host="+ host + ", port=" + port + " TLS = " + useTLS + " username=" + username + " password=" + password);
mqtt.connect(options);
}
function onConnect() {
$('#status').val('Connected to ' + host + ':' + port);
// Connection succeeded; subscribe to our topic
mqtt.subscribe(topic, {qos: 0});
$('#topic').val(topic);
}
function onConnectionLost(response) {
setTimeout(MQTTconnect, reconnectTimeout);
$('#status').val("connection lost: " + responseObject.errorMessage + ". Reconnecting");
};
function onMessageArrived(message) {
var topic = message.destinationName;
var payload = message.payloadString;
$('#ws').prepend('<li>' + topic + ' = ' + payload + '</li>');
};
$(document).ready(function() {
MQTTconnect();
});
</script>
</head>
<body>
<h1>Mosquitto Websockets</h1>
<div>
<div>Subscribed to <input type='text' id='topic' disabled />
Status: <input type='text' id='status' size="80" disabled /></div>
<ul id='ws' style="font-family: 'Courier New', Courier, monospace;"></ul>
</div>
</body>
</html>
I get
WebSocket connection to 'ws://127.0.0.1:1883/mqtt' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET mqttws31-min.js:15
Host=127.0.0.1, port=1883 TLS = false username=null password=null (index):47
I am new to this so am unable to resolve this. Any help?
Edit1:
I tweaked the config file and now it successfully connects to test.mosquitto.org:8080. I subscribed to #, but it is unable to retrieve the published message. I think function onMessageArrived(message) is not working. There are no errors in the console so unable to identify any errors.
Are you sure that you have configured the broker to accept websockets connections on port 1883? By default you would expect this to be listening for MQTT connections, not websockets.
Try putting the following in your config file:
listener 8080
protocol websockets
As Scott says, you could try connecting your client to test.mosquitto.org:8080 to see if it works.
Here is a site which runs a "MQTT over Websockets" server where the URL can act as a client so you can publish, then have your own browser act as a client subscribing to given topic
http://test.mosquitto.org/ws.html
it might let you tease apart connection issues ... also here is another nodejs library which implements similar functionality
https://www.npmjs.com/package/mqtt-ws
Based on your comment #toothie
"I tried connecting to 'test.mosquitto.org' and got this error: WebSocket connection to 'ws://test.mosquitto.org/:1883/mqtt' failed: Error during WebSocket handshake: Unexpected response code: 404"
The connection string you are sending seems bad formatted. How are you building it?
For me, the separation of concerns using the JSON object definition to instance the library saved me from a couple of headaches:
{
protocol: 'wss',
host: `${process.env.MQTT_ENDPOINT}`,
port: 9001,
username: 'admin',
password: '123'
}
Maybe something is helpful for you.

Fetch terminal command (Nodejs) and send to specific port via AJAX

I'm actually working on a little application. I have one server written in C which is listening on the port 5260. In the other side I have a NodeJS client which is listening on the port 7777. A HTML page can be reach via this port. In the HTML page I have a simple button.
When I click on this one a message is sent to my NodeJS server and is written on the terminal. Now I would like to fetch this command and send it to my C server which is still running and waiting for a request.
My client.js :
var http = require('http');
var ejs = require('ejs');
var express=require('express');
var app = express();
app.engine('html', ejs.renderFile);
app.set('/', __dirname);
app.get('/', function(request,response) {
response.render('index.ejs.html');
})
var options = {
host: '192.168.1.154',
path: '/',
port: '5260',
method: 'POST'
};
app.post('/play', function(req, res){
var res = http.request(options);
console.log("START_BG;BG1\n");
});
app.listen(7777);
And my HTML file :
<html>
<head>
<script type="text/javascript" src="client.js"></script>
<script type="text/javascript">
function sendMessage() {
var xhr = new XMLHttpRequest();
xhr.open('POST', '/play', true);
xhr.onload = function() {
console.log(xhr);
};
xhr.send();
}
</script>
</head>
<body>
<button onclick="sendMessage()">VIDEO</button>
</body>
</html>
Well. I see some strange things in your code
1 You're making the post request to 192.168.1.254:5620/play without sending any data on it
2 You're not waiting fro the request to end and blindly print on your console without checking the result. Don't know if its the desired behaviour, but it seems a bit strange
Without more knowledge about the scenario is difficult to suggest an idea.
What is the answer you expect from the remote server?
It's suposed to print something in the (remote) console ?
What it should return via HTTP ?
Anyway I suggest you correct your code as follows:
app.post('/play', function(req, res){
var res = http.request(options, function(response){
// do any checking about response status and/or body if any
console.log("START_BG;BG1\n");
});
});

socket.io - Basic example usage error, io not defined error

I am running node v0.5.11 pre
and installed socket.io. I have also install socket.io version 0.9.1
I am running server standard.
var io = require('socket.io').listen(8080);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
which is standard server and following is client ..
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('171.69.117.215:8080');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
when I load client in Firefox using port 80 from server 171.69.117.215 I get in Firebug following error:
io is not defined
[Break On This Error]
var socket = io.connect('171.69.117.215:8080');
I know it is deployment issue as I am loading from port 80 client, which is right way to deploy socket.io application ?
Thanks in advance.
Please insert into client code ..Point to your on node.js server.
<script src="http://yournodeserver/socket.io/socket.io.js"></script>

Resources