I am unable to connect to my local Mosquitto 1.4.10 broker from a JavaScript client over a Websocket.
The same JavaScript client is successfully connecting to the public broker at test.mosquitto.org on port 8080 over a Websocket.
The MQTT protocol connection on port 1883 is working fine, which I tested using mosquitto_pub and mosquitto_sub.
My broker is set up within a VirtualBox running Ubuntu 14.04.
I have libwebsockets installed on the same virtual machine.
My local broker was compiled with WITH_WEBSOCKETS:=yes in the config.mk file
I am loading the JavaScript client web page from the same virtual machine from a Firefox browser and seeing the following error message in the browser console:
Firefox can't establish a connection to the server at
ws://localhost:8080/mqtt
Your suggestions on fixing this will be greatly appreciated.
Thanks.
Here is my Mosquitto .conf file:
port 1883
listener 8080
protocol websockets
log_type all
websockets_log_level 1023
connection_messages true
Here is the Mosquitto server's log (with websockets logging level set to 1023, and verbose logging turned on - no messages appear when I load the JavaScript web page):
1481381105: mosquitto version 1.4.10 (build date 2016-12-10
18:47:37+0530) starting
1481381105: Config loaded from /etc/mosquitto/mosquitto.conf.
1481381105: Opening websockets listen socket on port 8080.
1481381105: Initial logging level 1023
1481381105: Libwebsockets version: 2.1.0 manavkumarm#manav-alljoyn
1481381105: IPV6 not compiled in
1481381105: libev support not compiled in
1481381105: libuv support not compiled in
1481381105: Threads: 1 each 1024 fds
1481381105: mem: platform fd map: 4096 bytes
1481381105: Compiled with OpenSSL support
1481381105: Creating Vhost 'default' port 8080, 3 protocols, IPv6 off
1481381105: Using non-SSL mode
1481381105: Listening on port 8080
1481381105: mem: per-conn: 376 bytes + protocol rx buf
1481381105: canonical_hostname = mqtt
1481381105: Opening ipv4 listen socket on port 1883.
1481381105: Opening ipv6 listen socket on port 1883.
Here is the JavaScript source code:
<html>
<body>
<script src="mqttws31.js"></script>
<script>
try
{
// Create a client instance
console.log("Creating client object...");
client = new Paho.MQTT.Client("localhost", Number(8080), "manav");
//client = new Paho.MQTT.Client("test.mosquitto.org", Number(8080), "manav");
// set callback handlers
console.log("Setting handlers...");
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
// connect the client
console.log("Connecting...");
client.connect( {
onSuccess: onConnect,
mqttVersion: 4
});
}
catch (e)
{
console.log("Error: " + e.description);
}
// called when the client connects
function onConnect()
{
// Once a connection has been made, make a subscription and send a message.
console.log("Connected");
setTimeout( function() {
client.subscribe("world");
message = new Paho.MQTT.Message("Hello");
message.destinationName = "world";
client.send(message);
//client.disconnect();
}, 5000);
}
// called when the client loses its connection
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("Connection lost: " + responseObject.errorMessage);
}
}
// called when a message arrives
function onMessageArrived(message) {
console.log("Received Message: " + message.payloadString);
client.disconnect();
}
</script>
<h1>My MQTT Websockets Example</h1>
</body>
</html>
I see I am little bit late on answer.
MQTT's port for websocket is 1884 or something else, you have 8080. Maybe thats the problem.
Isnt 8080 a reserved TCP port?
Also, I know you have javascript code, but its paho. I was able to make publisher(it uses same class like subscriber so it must be on subscriber side too - this is just assumption though) work on websockets with paho python client which must be initialized with defining transport parameter. -> communicating with browser(see below for javascript)
mqtt.Client(transport='websockets')
Leaving that parameter MQTT assumes using TCP
mqtt.Client()
Also:
Config on my broker:
# Place your local configuration in /etc/mosquitto/conf.d/
#
# A full description of the configuration file is at
# /usr/share/doc/mosquitto/examples/mosquitto.conf.example
pid_file /var/run/mosquitto.pid
persistence true
persistence_location /var/lib/mosquitto/
log_dest file /var/log/mosquitto/mosquitto.log
include_dir /etc/mosquitto/conf.d
listener 1883
listener 1884
protocol websockets
I found my very old Javascript with paho-mqtt. It was working, so I just put it here.
Its subscriber and publisher at the same time. Together with the config, It was working like charm.
class sub{
constructor(hostname,port,clientid,topic){
this.buffer = []
this.hostname=hostname;
this.port=port;
this.clientid = clientid;
this.topic = topic;
this.client = new Paho.MQTT.Client(hostname,port, clientid);
// set callback handlers
this.client.onConnectionLost = this.onConnectionLost;
this.client.onMessageArrived = this.onMessageArrived.bind(this);
// connect the client
this.client.connect({onSuccess:this.onConnect});
}
onConnect(){
console.log('OnConnect');
}
onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:"+responseObject.errorMessage);
}
}
onMessageArrived(message) {
console.log("onMessageArrived:"+message.payloadString);
this.buffer.push(JSON.parse(message.payloadString));
}
subsribe(){
this.client.subscribe(this.topic)
}
publish(message){
console.log(message)
var mg = new Paho.MQTT.Message(JSON.stringify(message));
mg.destinationName = this.topic;
this.client.send(mg);
}
}
var x
x = new sub('xx.xx.xx.xx',1884,'clientID','LED');
function on(){
x.publish({'LED':'ON'});
}
function off(){
x.publish({'LED':'OFF'});
}
Related
I am trying to make a wss connection using JavaScript(mqttws31.js) client with generated self signed certificate but unable to create a connection and getting the below error.
"Firefox can’t establish a connection to the server at wss://localhost:8883/mqtt."
"Error: AMQJS0011E Invalid state not connected."
I have included the MQTT broker configuration details and JavaScript script code for reference.
MQTT Broker configuration( mosquitto.conf ).
port 8084
persistence true
persistence_file mosquitto.db
listener 1883 localhost
protocol mqtt
listener 8883
protocol websockets
allow_anonymous true
require_certificate false
cafile C:/Program Files/mosquitto/certs/certs/ca.crt
certfile C:/Program Files/mosquitto/certs/certs/server.crt
keyfile C:/Program Files/mosquitto/certs/certs/server.key
tls_version tlsv1.2
Javascript Client Code:
Below are inputs passing to the function.
host: localhost , port : 8883 and clientID : 1234.
function(){
that.client = new Paho.MQTT.Client(host, Number(port), clientId);
console.log("Connecting to " + host);
that.client.onConnectionLost = onConnectionLost;
that.client.onMessageArrived = onMessageArrived;
that.client.connect({
onSuccess : onConnect,
userName: 'user',
password:'password',
useSSL: true,
cleanSession : false
});
}
function onConnect() {
console.log('onConnect:');
that.client.subscribe("mgtl/#", {
qos : 2,
onSuccess : function(){
console.log('Acknowldgement recieved by sender');
},
onFailure : function(){
console.log('Subscribe request has failed or timed out');
}
});
that.client.subscribe("local/ack", {qos : 0});
console.log('mqtt connected');
}
Can anyone provide me the solution.
As hashed out in the comments, it sounds like your browser didn't trust the CA you used to sign your brokers certificate.
Browsers do not pop up the same dialog about untrusted certificates as they do for HTTPS connection as they expect the code to make a decision about what to do with a connection failure (but I don't think they actually provide the reason in the error messages)
The best way to track this sort of thing down is usually to make sure you check the network tab in the browsers developer tools.
As to why Chrome is not liking the imported CA cert, it may depend on what OS you are on as Chrome uses the system cert store unlike Firefox that maintains it's own iirc.
I installed Mosquitto on a VM referring the following link
https://gist.github.com/smoofit/dafa493aec8d41ea057370dbfde3f3fc
The Mosquitto Broker is Up and shows
1565283316: mosquitto version 1.4.12 (build date 2019-08-08 15:47:50+0000) starting
1565283316: Config loaded from /etc/mosquitto/mosquitto.conf.
1565283316: Opening websockets listen socket on port 9001.
1565283316: Opening ipv4 listen socket on port 1883.
1565283316: Opening ipv6 listen socket on port 1883.
But not able to connect from the Paho Javascript Client
I tried installing the newest version of Mqtt with mosquitto. I allowed 9001 and 1883 ports on firewall but not able to connect.
Here is my JS Client Code.
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script>
</head>
<script>
// Create a client instance
client = new Paho.MQTT.Client(IPAddress, Number(9001), "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>
Please help me fix this. Thanks in advance
I am building a system using an ESP8266/NodeMcu module (similar to an Arduino, just with networking capabilities) and a NodeJs server running on the local network.
To discover the IP address of the server, I'm trying to use UDP broadcasting on the NodeMcu module. The idea is to send out a message on the local broadcasting IP (e.g. 192.168.1.255). The server then receives the message and sends a response, confirming that it is the server. This way, the NodeMcu knows the direct address of the server for further communication.
The problem is, that the server is completely flooding itself with the same message whenever it receives the first message from the NodeMcu, while the NodeMcu actually sends out a message only once a second.
It looks like this on the NodeMcu side:
[UDP] Sending UDP Broadcast on IP: 192.168.43.255, Port: 8080, Message: ESP8266 UDP Server Discovery Broadcast
The server outputs something like this, many times a second:
[10:33:07] 127.0.0.1:8080 # service discovery : ESP8266 UDP Server Discovery Broadcast
[10:33:07] 127.0.0.1:8080 # service discovery : ESP8266 UDP Server Discovery Broadcast
[10:33:07] 127.0.0.1:8080 # service discovery : ESP8266 UDP Server Discovery Broadcast
It doesn't make sense that it's receiving that many messages, especially because it's apparently coming from 127.0.0.1 and not the IP of the NodeMcu. It also doesn't send out any response.
I tried to receive the broadcast on my phone with a UDP Monitor app, an application called Packet Sender and the Linux Terminal. It all worked fine, and sending a manual response triggered the acknowledgement on the NodeMcu.
So I'm thinking there has to be some kind of error with the server, or with the network I'm using. The server is running on Linux on my computer, while I'm hosting the network via a hotspot on my phone (my real WiFi network blocked UDP broadcasting). The Linux firewall is turned off.
I'm no expert in JavaScript or NodeJs by any means and the server was written by someone I'm working with, but he has no clue either. Anyway, this is the important part on the server:
client.on('listening', function () {
var address = client.address();
debugMessage(
format('Service discovery running on port %s', config.port)
);
client.setBroadcast(true);
});
client.on('message', function (message, rinfo) {
debugMessage(
format('%s:%s # service discovery : %s', rinfo.address, rinfo.port, message)
);
client.send(message, 0, message.length, rinfo.port, rinfo.ip);
});
client.bind(config.port);
The code on the NodeMcu looks like this:
#include <ESP8266WiFi.h> // WiFi library
#include <WiFiUdp.h> // UPD functionality
// UDP variables
WiFiUDP udp;
unsigned int localUdpPort = 8080;
char incomingPacket[255];
const char broadcastMessage[] = "ESP8266 UDP Server Discovery Broadcast";
// Server details - written to when the server is found
IPAddress serverIp = ~WiFi.subnetMask() | WiFi.gatewayIP(); // Use Broadcast Address as default in case the UDP service discovery isn't working as intended
unsigned int serverPort = localUdpPort; // Use local port as default in case the UDP service discovery ins't working as intended
void setupWiFi()
{
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
#if LOGGING
Serial.println("Connecting to network: " + (String) WIFI_SSID);
#endif
while (WiFi.status() != WL_CONNECTED)
{
delay(100);
}
#if LOGGING
Serial.print("Connected to network, Local IP Address: ");
Serial.println(WiFi.localIP());
#endif
udp.begin(localUdpPort); // begin listening on UDP port
#if LOGGING
Serial.printf("Now listening at IP %s, UDP port %d\n", WiFi.localIP().toString().c_str(), localUdpPort);
#endif LOGGING
}
// Discover the server via a UDP broadcast, and store it's IP and Port in the local network in field variables for later use
// IMPORTANT - For the server to work, the Linux Firewall has to be disabled!!!
void discoverServer()
{
changeColor(PURPLE, false); // change the color of the RGB status LED to signal that the program is searching for the server
bool serverFound = false; // stop when the server is found
IPAddress broadcastIp = ~WiFi.subnetMask() | WiFi.gatewayIP(); // Get the Broadcast IP of the local network (e.g. 192.168.0.255)
while (!serverFound)
{
// Send UDP Broadcast
udp.beginPacket(broadcastIp, localUdpPort);
udp.write(broadcastMessage);
udp.endPacket();
#if LOGGING
Serial.printf("[UDP] Sending UDP Broadcast on IP: %s, Port: %d, Message: %s\n", broadcastIp.toString().c_str(), localUdpPort, broadcastMessage);
#endif
delay(1000); // Pause a few milliseconds to avoid flooding the network
// Receive UDP packets
int packetSize = udp.parsePacket();
if (packetSize > 0)
{
// Read incoming UDP Packet
int len = udp.read(incomingPacket, 255);
if (len > 0)
{
incomingPacket[len] = 0;
}
#if LOGGING
Serial.printf("[UDP] Received %d bytes from %s, port %d\n", packetSize, udp.remoteIP().toString().c_str(), udp.remotePort());
Serial.printf("[UDP] Packet contents: %s\n", incomingPacket);
#endif
// Check if the received message is from the server we are searching for
if (strcmp(incomingPacket, broadcastMessage) == 0)
{
serverIp = udp.remoteIP();
serverPort = udp.remotePort();
#if LOGGING
Serial.printf("[UDP] Found Server on IP: %s, Port: %d\n", serverIp.toString().c_str(), serverPort);
#endif
serverFound = true;
changeColor(YELLOW, false); // Change status color of RGB LED back to yellow
}
}
}
}
I'm really wondering if there is something wrong with the server, the network or the NodeMcu. Especially because every other method I tried worked perfectly, just not when I'm sending it from the NodeMcu. Any help is very much appreciated!
It turned out that there was an error in the server code.
Instead of
client.send(message, 0, message.length, rinfo.port, rinfo.ip);
it should have been
client.send(message, 0, message.length, rinfo.port, rinfo.address);
The server didn't know rinfo.ip, so it spammed itself with the same message over and over again.
I am using Aurora 17, Chrome 22 and Firefox 16 and I am trying to create a simple chat app. I am using Node 0.8.9.
Firefox is getting the error that it cannot connect giving the error
Firefox can't establish a connection to the server at ws://localhost/.
I also tried it with the port and it have the same message
Firefox can't establish a connection to the server at ws://localhost:4444/.
Here is my code:
Server Code:
var http = require('http');
var net = require('net');
function onRequest(req, res) {
// Does enough to render a page and javascript
}
http.createServer(onRequest).listen(4444);
var socket = new net.Socket();
socket.connect(4444, "localhost", function(){
console.log("Socket Connected");
});
socket.on("message", function(message){
console.log(message);
});
Client Code:
var WebSocket = window.WebSocket || window.MozWebSocket;
var connection = new WebSocket('ws://localhost:4444');
connection.onopen = function() {
// Never runs
alert("This never runs :(")
}
connection.onerror = function(error) {
// Always runs here
console.log(error)
}
I get an output that the Socket is connect from the log statement on the server but Firefox cannot connect to the socket.
On Chrome, there is no error but the "onopen" is never fired. Using connection.send("a message") does not send anything to the server and returns false.
You're creating an ordinary TCP client socket in your server code and connecting it to your HTTP server. That's not at all the same thing as creating a WebSocket server that a browser can connect to. Use a library designed for the purpose (socket.io is very commonly used, since it can fall back to alternate transports when a browser doesn't support WebSockets).
Question: Is it possible to cluster an application which is using Socket.io for WebSocket support? If so what would be the best method of implementation?
I've built an application which uses Express and Socket.io, built on Node.js. I'd like to incorporate clustering to increase the amount of requests that my application can process.
The following causes my application to produce a socket handshake error...
var cluster = require('cluster');
var numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
// Fork workers.
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('death', function(worker) {
console.log('worker ' + worker.pid + ' died');
});
} else {
app.listen(3000);
}
A console log shows that socket.io is being started up multiple times.
jack#jack:~$ node nimble/app.js
info - socket.io started
info - socket.io started
info - socket.io started
info - socket.io started
info - socket.io started
info - socket.io started
info - socket.io started
info - socket.io started
info - socket.io started
Socket.io is currently being set up in the top of my server code using:
var io = require('socket.io').listen(app);
The websocket authorization code:
//Auth the user
io.set('authorization', function (data, accept) {
// check if there's a cookie header
if (data.headers.cookie) {
data.cookie = parseCookie(data.headers.cookie);
data.sessionID = data.cookie['express.sid'];
//Save the session store to the data object
data.sessionStore = sessionStore;
sessionStore.get(data.sessionID, function(err, session){
if(err) throw err;
if(!session)
{
console.error("Error whilst authorizing websocket handshake");
accept('Error', false);
}
else
{
console.log("AUTH USERNAME: " + session.username);
if(session.username){
data.session = new Session(data, session);
accept(null, true);
}else {
accept('Invalid User', false);
}
}
})
} else {
console.error("No cookie was found whilst authorizing websocket handshake");
return accept('No cookie transmitted.', false);
}
});
Console log of the error message:
Error whilst authorizing websocket handshake
debug - authorized
warn - handshake error Error
What is your sessionStore? If it's the MemoryStore shipped with connect, then sessions won't be shared between your workers. Each worker will have it's own set of sessions, and if a client connects to another worker, you wont find their session. I suggest you take a look at e.g. connect-redis for sharing sessions between processes. Basic usage:
var connect = require('connect')
, RedisStore = require('connect-redis')(connect);
var app = connect.createServer();
app.use(connect.session({store: new RedisStore, secret: 'top secret'});
Of course, this requires that you also set up redis. Over at the Connect wiki there are modules for CouchDB, memcached, postgres and others.
This only solves part of your problem, though, because now you have sessions shared between workers, but socket.io has no way of sending messages to clients which are connected to other workers. Basically, if you issue a socket.emit in one worker, that message will only be sent to clients connected to that same worker. One solution to this is to use RedisStore for socket.io, which leverages redis to route messages between workers. Basic usage:
var sio = require('socket.io')
, RedisStore = sio.RedisStore
, io = sio.listen(app);
io.set('store', new RedisStore);
Now, all messages should be routed to clients no matter what worker they are connected to.
See also: Node.js, multi-threading and Socket.io