Not able to connect to Mosquitto Server from mqtt.js - javascript

I am new to wqtt server. I am trying to connect to mosquitto test server using mqtt.js reffering an example provided on their website.
But i am not able to connect to the server. I always get following error:
WebSocket connection to 'ws://test.mosquitto.org/:8080/mqtt' failed: Error in connection establishment: net::ERR_NAME_NOT_RESOLVED.
Please help. Below is my html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="http://www.hivemq.com/demos/websocket-client/js/mqttws31.js" type="text/javascript"></script>
<title>HiveMQ MQTT Websocket Demo App</title>
<script type="text/javascript">
var client = new Messaging.Client("test.mosquitto.org", 8080, "myclientid_" + parseInt(Math.random() * 100, 10));
//Gets called if the websocket/mqtt connection gets disconnected for any reason
client.onConnectionLost = function (responseObject) {
//Depending on your scenario you could implement a reconnect logic here
alert("connection lost: " + responseObject.errorMessage);
};
//Gets called whenever you receive a message for your subscriptions
client.onMessageArrived = function (message) {
//Do something with the push message you received
$('#messages').append('Topic: ' + message.destinationName + ' | ' + message.payloadString + '');
};
//Connect Options
var options = {
timeout: 3,
//Gets Called if the connection has sucessfully been established
onSuccess: function () {
alert("Connected");
},
//Gets Called if the connection could not be established
onFailure: function (message) {
document.write("Connection failed: " + message.errorMessage);
alert("Connection failed: " + message.errorMessage);
}
};
//Creates a new Messaging.Message Object and sends it to the HiveMQ MQTT Broker
var publish = function (payload, topic, qos) {
//Send your message (also possible to serialize it as JSON or protobuf or just use a string, no limitations)
var message = new Messaging.Message(payload);
message.destinationName = topic;
message.qos = qos;
client.send(message);
}
</script>
</head>
<body>
<button onclick="client.connect(options);">1. Connect</button>
<button onclick="client.subscribe('testtopic/#', {qos: 2}); alert('Subscribed');">2. Subscribe</button>
<button onclick="publish('Hello Foo !','testtopic/bar',2);">3. Publish</button>
<button onclick="client.disconnect();">(4. Disconnect)</button>
<div id="messages"></div>
</body>

From your error message I can see 2 issues.
test.mosquitto.org listens for Websocket connections on 8080 not 1883
There should be no http:// in the url to connect to a websocket server
Also the error message does not match the details you have included in the code sample.

Related

Why cannot I connect to hivemq broker the socket keep on getting closed when I try to reconnect?

I have wriiten to publish a rfid value and while subscribing inside javascript, the socket connection is lost and I have attached the screenshot of my console.
value.php
<body>
<div id="print"></div>
<!-- jquery library -->
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<!-- paho MQTT library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script>
<script src="app.js"></script>
</body>
I am trying to connect using hivemq broker and using port number of 8000 but it's not connecting.
app.js
var hostname = "broker.hivemq.com";
var clientId = "someid";
var username = "username";
var password = "password";
var subscription = "sometopicname";
mqttClient = new Paho.MQTT.Client(hostname, 8000, clientId);
mqttClient.onMessageArrived = MessageArrived;
mqttClient.onConnectionLost = ConnectionLost;
Connect();
function Connect() {
mqttClient.connect({
onSuccess: Connected,
onFailure: ConnectionFailed,
userName: username,
password: password,
useSSL: false
});
}
function Connected() {
console.log("Connected");
mqttClient.subscribe(subscription);
}
function ConnectionFailed(res) {
console.log("Connection failed: " + res.errorMessage);
}
function ConnectionLost(res) {
if (res.errorCode !== 0) {
console.log("Connection lost:" + res.errorMessage);
Connect();
}
}
function MessageArrived(message) {
console.log(message.payloadString);
}
First, are you 100% sure that port 8000 is configured to support MQTT over Websockets.
Second, you appear to have a hard coded clientId value, with this you will only be able to have 1 client connected at a time. EVERY Page needs to have a unique clientId, if you try and connect 2 clients with the same clientId (2 or more instances of the page in any browser) will kick the other one off the broker. ClientIds MUST be globally unique.
If after you have checked the first and fixed the second you should check the broker logs to see why it may be closing the connection.

How do I define Watershed in Node.js?

When I execute the following code, I get the error: Reference Error: Watershed is not defined. How can I define it? Do I need a module to be installed for it?
var restify=require('restify');
var ws= new Watershed();
var server=restify.createServer();
server.get('websocket/attach', function upgradeRoute(req, res, next){
if(!res.claimUpgrade){
next(new Error("Connection must be upgraded."));
return;
}
var upgrade=res.claimUpgrade();
var shed=ws.accept(req, upgrade.socket, upgrade.head);
shed.on('text', function (msg){
console.log("The message is: "+msg);
});
shed.send("hello there");
next(false);
});
server.listen(8081, function(){
console.log('%s listening at %s', server.name, server.url);
});
There is also a section of the restify doc that mentioned how to handle the ability to upgrade sockets. I just struggled with this for an emarrassingly long time and thought I'd share the simple solution. In addtion the #Dibu Raj reply, you also need to create your restify server with the handleUpgrades option set to true. Here is a complete example to make restify work with websocket upgrades and watershed:
'use strict';
var restify = require('restify');
var watershed = require('watershed');
var ws = new watershed.Watershed();
var server = restify.createServer({
handleUpgrades: true
});
server.get('/websocket/attach', function (req, res, next) {
if (!res.claimUpgrade) {
next(new Error('Connection Must Upgrade For WebSockets'));
return;
}
console.log("upgrade claimed");
var upgrade = res.claimUpgrade();
var shed = ws.accept(req, upgrade.socket, upgrade.head);
shed.on('text', function(msg) {
console.log('Received message from websocket client: ' + msg);
});
shed.send('hello there!');
next(false);
});
//For a complete sample, here is an ability to serve up a subfolder:
server.get(/\/test\/?.*/, restify.serveStatic({
directory: './static',
default: 'index.html'
}));
server.listen(8080, function() {
console.log('%s listening at %s', server.name, server.url);
});
For an html page to test your new nodejs websocket server: write this html below into a file at ./static/test/index.html - point your browser to http://localhost:8080/test/index.html - open your browser debug console to see the message exchange.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Web Socket test area</title>
<meta name="description" content="Web Socket tester">
<meta name="author" content="Tim">
</head>
<body>
Test Text.
<script>
(function() {
console.log("Opening connection");
var exampleSocket = new WebSocket("ws:/localhost:8080/websocket/attach");
exampleSocket.onopen = function (event) {
console.log("Opened socket!");
exampleSocket.send("Here's some text that the server is urgently awaiting!");
};
exampleSocket.onmessage = function (event) {
console.log("return:", event.data);
exampleSocket.close();
}
})();
</script>
</body>
</html>
Your browser log will look something like this:
07:05:05.357 index.html:18 Opening connection
07:05:05.480 index.html:22 Opened socket!
07:05:05.481 index.html:26 return: hello there!
And your node log will look like:
restify listening at http://[::]:8080
client connected!
Rest service called started
upgrade claimed
Received message from websocket client: Here's some text that the server is urgently awaiting!
Documentation for this found at:
http://restify.com/#upgrade-requests
You should include the watershed library
var Watershed = require('lib/watershed').Watershed;

Websockets over WSS:// doesn't appear to fire events on server

I am trying to set up a basic WSS websockets server. This is my minimal HTML (with the embedded javascript):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test</title>
</head>
<body style="background-color:white">
<h1>Test of WSS server</h1>
<p>Status: <span id=status"></span></p>
Click to send message
<script src="/newjs/jquery-2.1.1.js"></script>
<script>
var connection;
$(document).ready(function () {
window.WebSocket = window.WebSocket || window.MozWebSocket;
if (!window.WebSocket) {
alert("browser says no");
console.log("Browser does not supports websockets");
return;
}
setupConnection();
});
function message() {
var msg = "Test Message";
connection.send(msg);
}
function setupConnection() {
connection = new WebSocket('wss://www.example.com:14000');
connection.onerror = function(error) {
console.log('onerror fired');
};
connection.onopen = function(event) {
$("#status").html("Open");
};
connection.onmessage = function (message) {
alert(message.data);
};
}
setInterval(function() {
if (connection.readyState !== 1) {
setupConnection();
}
}, 5000);
</script>
</body>
</html>
The following is the JS server run by nodejs:
var fs=require("fs");
var ws_cfg = {
ssl: true,
port: 14000,
ssl_key: '/httpd/conf/ssl.key/my.key',
ssl_cert: '/httpd/conf/ssl.crt/my.crt',
ca_cert: '/httpd/conf/ssl.crt/gd_bundle-g2-g1.crt'
};
var processRequest = function(req, res) {
console.log("Request received.")
};
var httpServ = require('https');
var app = null;
app = httpServ.createServer({
key: fs.readFileSync(ws_cfg.ssl_key),
cert: fs.readFileSync(ws_cfg.ssl_cert),
ca: fs.readFileSync(ws_cfg.ca_cert),
},processRequest).listen(ws_cfg.port);
var WebSocketServer = require('ws').Server, ws_server = new WebSocketServer( {server: app});
ws_server.on('open',function(request) {
console.log("opening");
});
ws_server.on('request', function(request) {
console.log((new Date()) + ' Connection from origin ' + request.origin + '.');
if (request.origin!='https://www.example.com') {
console.log("rejecting request from " + request.origin + " as not coming from our web site");
return;
}
var connection = request.accept(null, request.origin);
connection.on('message', function(message) {
console.log("Got a message");
});
});
I fire up the server with node then load the web page in my browser (using either FF or Chrome). Using the developer tools I see that the connection appears to be made. On the server side I see the established connection using netstat. I also put an alert() in the browser side in the onopen() function and it fired.
The problem is that no console log output is produced. When connection.send(mag) is executed the on("message" event never appears to fire on the server. I'm at a loss here. I had this working as an http:// websocket server but this is my first attempt at wss:. I would appreciate any insight.
Notes:
The sever name is not example.com although that is what I show in my code.
The firewall is allowing anyone to connect on port 14000 using TCP protocol.
The cert is a working wildcard cert for the web site.
Finally figured out what it was after ignoring it for a month or so. It had to do with the symbolic link (/httpd) defined for the SSL files as in:
ssl_key: '/httpd/conf/ssl.key/my.key',
ssl_cert: '/httpd/conf/ssl.crt/my.crt',
They had to be changed to:
ssl_key: '/usr/local/apache2/conf/ssl.key/my.key',
ssl_cert: '/usr/local/apache2/conf/ssl.crt/my.crt',
Who knew that symbolic links were frowned upon? Well, now we all do.

MQTT for Web Application

I was trying to develop a simple web application using the MQTT Broker. I used Mosca as the broker on localhost. First I tried out a program copied from the web to see how MQTT works. This is the program.
home.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<script src="mqttws31.js" type="text/javascript"></script>
<script src="client.js">
</script>
</head>
<body onload="init();">
</body>
</html>
client.js
var wsbroker = "127.0.0.1"; //mqtt websocket enabled broker
var wsport = 3000 // port for above
var client = new Paho.MQTT.Client(wsbroker, wsport,
"myclientid_" + parseInt(Math.random() * 100, 10));
client.onConnectionLost = function (responseObject) {
alert("connection lost: " + responseObject.errorMessage);
};
client.onMessageArrived = function (message) {
alert(message);//.destinationName, ' -- ', message.payloadString);
};
var options = {
timeout: 3,
onSuccess: function () {
alert("mqtt connected");
// Connection succeeded; subscribe to our topic, you can add multile lines of these
client.subscribe('temp/random', {qos: 1});
//use the below if you want to publish to a topic on connect
message = new Paho.MQTT.Message("Hello");
message.destinationName = "/World";
client.send(message);
},
onFailure: function (message) {
alert("Connection failed: " + message.errorMessage);
}
};
function init() {
client.connect(options);
}
This program worked when I tried to access home.html in te web browser. I could see the log being generated in Mosca's console too. However, as visible, this program wasn't a very neat example. For that reason I tried to make a few changes to make the code readable.
This is my code after I made the changes -
home.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<script src="mqttws31.js" type="text/javascript"></script>
<script src="client.js">
</script>
</head>
<body onload="init();">
</body>
</html>
client.js
var wsbroker = "127.0.0.1";
var wsport = 3000
var client = new Paho.MQTT.Client(wsbroker, wsport,"myclientid_" + parseInt(Math.random() * 100, 10));
function onMessageArrived(message) {
document.write(message.payload);
};
function onSuccess() {
document.write("Connected");
client.subscribe('temp/random');
};
function onFailure(message) {
document.write("Connection Failed. Error : " + message.errorMessage);
};
function onConnectionLost(message) {
document.write("Connection Lost. Error : " + message.errorMessage);
};
var options = {
timeout: 3,
onSuccess: onSuccess,
onFailure = onFailure
};
function init() {
client.connect(options);
client.onMessageArrived = onMessageArrived,
client.onConnectionLost = onConnectionLost,
};
I have got a Python script running which publishes value. However, no output is being generated. I checked the Mosca console and noted that no new connections were made. I have just started learning Javascript. I am not sure if my new code is syntactically correct.
Couple changes will fix this.
First, you have onFailure = instead of onFailure:
Next, you want to set your client.onMessageArrived and client.onConnectionLost before you call connect, not after.
Those 2 changes result in
var wsbroker = "127.0.0.1";
var wsport = 3000
var client = new Paho.MQTT.Client(wsbroker, wsport,"myclientid_" + parseInt(Math.random() * 100, 10));
function onMessageArrived(message) {
document.write(message.payload);
};
function onSuccess() {
document.write("Connected");
client.subscribe('temp/random');
};
function onFailure(message) {
document.write("Connection Failed. Error : " + message.errorMessage);
};
function onConnectionLost(message) {
document.write("Connection Lost. Error : " + message.errorMessage);
};
var options = {
timeout: 3,
onSuccess: onSuccess,
onFailure: onFailure,
};
function init() {
console.log('connecting')
client.onMessageArrived = onMessageArrived,
client.onConnectionLost = onConnectionLost,
client.connect(options);
};

Connection closed before receiving a handshake response

i write a node program,and i encounter a big difficult.
the server side code is below:
var express=require("express");
var app=express();
var socketio=require("socket.io");
var server=require("http").Server(app);
var ws=socketio.listen(server);
app.use(express.static('public'));
app.listen(3000);
ws.on('connection',function(socket){
socket.on("message",function(msg){
console.log("got:"+msg);
socket.send('pong');
});
});
the client side code is below:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>websocket echo</title>
</head>
<body>
<h1>websocket echo</h1>
<h2>latency:<span id="latency"></span>ms</h2>
<script>
var lastMessage;
window.onload=function(){
//create socket
var ws=new WebSocket("ws://127.0.0.1:3000");
ws.onopen=function(){
//send first ping
ping();
};
// 监听Socket的关闭
ws.onclose = function(event) {
console.log('Client notified socket has closed',event);
};
ws.onmessage=function(ev){
console.log("got:"+ev.data);
document.getElementById("latency").innerHTML=new Date-lastMessage;
ping();
};
function ping(){
lastMessage= + new Date;
ws.send("ping");
}
}
</script>
</body>
</html>
there is the tip in chrome console:
WebSocket connection to 'ws://127.0.0.1:3000/' failed: Connection closed before receiving a handshake response (index):16
Client notified socket has closed CloseEvent
As mentioned in the comments this happens because socket.io should be connected with it's own client. You should either use websockets or socket.io on both sides.

Categories

Resources