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
Related
hey guys so i have this email provider called https://emailfake.com/channel6/ i want a script that will listen for all ws comming messages for already opened connections
const socket = new WebSocket('wss://emailfake.com');
// Listen for messages
socket.addEventListener('message', (event) => {
console.log('Message from server ', event.data);
});
note : a script that will work on console of devtools
I'm trying to connect two node.js servers via websocket using the ws package. Here is some code:
Client server:
var socket = new WebSocket("wss://localhost:9000");
socket.addEventListener('open', function (event) {
console.log("websocket connected");
})
socket.addEventListener('message', function (event) {
console.log("message from backend server: ", event.data);
})
Backend server:
var https = require('https');
var httpsServer = https.createServer(credentials, app);
const WebSocket = require('ws');
const wss = new WebSocket.Server({ server:httpsServer });
wss.on('connection', function (ws) {
console.log("websocket connnected");
})
httpsServer.listen(9000, function () {
console.log(`server started on port 9000 via https`);
});
When I run this code, a get an error message on the command prompt that says "Error: certificate has expired". I am using a self-signed ssl certificate, which works perfectly fine for a websocket between a node.js server and the browser so I'm not convinced there's anything wrong with the certificate. I've seen examples of how to make this work using socket.io and socket.io-client, but how can I make it work using the ws package?
This is a problem with the ssl certificate. For some reason, going from browser to node.js server using a self-signed ssl certificate is fine, but going from node.js server to node.js using a self-signed ssl certificate is not.
I created a brand new ssl certificate and then in the client server, instead of:
var socket = new WebSocket("wss://localhost:9000");
.. I now have:
var socket = new WebSocket("wss://localhost:9000", {
rejectUnauthorized: false
});
..and it works.
server
var io = require('socket.io'),
UUID = require('node-uuid'),
gameport = 3000;
var db = {
waiting_clients: []
};
var logic = {
};
var sio = io.listen(gameport);
sio.sockets.on('connection', function(socket){
var client = {
id: UUID()
};
socket.emit('news', client);
console.log(client.id);
db.waiting_clients.push(client);
});
test client:
var net = require('net');
var client = net.connect({port: 3000},
function(e) { //'connect' listener
console.log('client connected');
client.end();
});
in test client console, it show "client connected". But there are no output in server console
You must use a socket.io client to connect to a socket.io server. Your code shows that you are trying to make a generic TCP connection to a socket.io server. That will not work. The lowest level connection will be established, but then the initial protocol handshake will fail and the socket.io server will drop the connection and you will never get the connection event.
Socket.io has its own connection scheme built on top of webSocket which is built on top of HTTP which is built on top of TCP.
So, to connect to a socket.io server, you must use a socket.io client that runs both the socket.io and webSocket protocol, not a plain TCP socket.
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'
};
I want to use sockets in my web app. I don't want to use socket.io library on client-side. It's OK for server-side though. Can I do this?
Now with socket.io on server and pure websocket on client I have destroying non-socket.io upgrade error. I've googled that it means that I have to use socket.io-client library on client-side. Is there any way to avoid that? I don't want client to be tight with this library and use pure html5 websocket instead.
If it's not possible what should I use for server to connect with pure html5 websockets?
If someone is curious here is my server code (coffeescript file)
# Require HTTP module (to start server) and Socket.IO
http = require 'http'
io = require 'socket.io'
# Start the server at port 8080
server = http.createServer (req, res) ->
# Send HTML headers and message
res.writeHead 200, { 'Content-Type': 'text/html' }
res.end "<h1>Hello from server!</h1>"
server.listen 8080
# Create a Socket.IO instance, passing it our server
socket = io.listen server
# Add a connect listener
socket.on 'connection', (client) ->
# Create periodical which ends a message to the client every 5 seconds
interval = setInterval ->
client.send "This is a message from the server! #{new Date().getTime()}"
, 5000
# Success! Now listen to messages to be received
client.on 'message', (event) ->
console.log 'Received message from client!', event
client.on 'disconnect', ->
clearInterval interval
console.log 'Server has disconnected'
And here is a client-side
<script>
// Create a socket instance
socket = new WebSocket('ws://myservername:8080');
// Open the socket
socket.onopen = function (event) {
console.log('Socket opened on client side', event);
// Listen for messages
socket.onmessage = function (event) {
console.log('Client received a message', event);
};
// Listen for socket closes
socket.onclose = function (event) {
console.log('Client notified socket has closed', event);
};
};
</script>
I've found this library, seems OK for my needs https://npmjs.org/package/ws