1

I want to make a simple client server example with visual studio code. For my mqtt client instance, mosca didn't work. So I created a server with aedes. However, it is not possible to connect to client.js at the moment. I'm sure it's missing on the server side, but I'm not sure how to fix it. I'm very new to this. my codes are below.

Server;

const aedes = require('aedes')()
const server = require('net').createServer(aedes.handle)
const httpServer = require('http').createServer()
const ws = require('websocket-stream')
const port = 1883
const wsPort = 3000

server.listen(port, function () {
  console.log('server started and listening on port ', port)
})

ws.createServer({ server: httpServer }, aedes.handle)

httpServer.listen(wsPort, function () {
  console.log('websocket server listening on port ', wsPort)
})

Client;

var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://192.168.43.40:1883');

client.subscribe('new-user');

client.on('connect', function() {
    console.log('connected!');

    client.publish('new-user', 'Cansu-' + Math.ceil(Math.random() * 10));
});

client.on('message', function(topic, message) {
    console.log(topic, ' : ', message.toString());
    client.end();
});

Thank You!!!

cans
  • 67
  • 7
  • Please add more information on how you are running this (node/browser) and any error messages. If the client is running in a browser then you will need to use websockets. – Brits Feb 24 '21 at 19:26
  • Assuming you move the `client.subscribe()` to inside the `client.on('connect',...)` callback that code works just fine. I suspect you probably have a firewall problem. – hardillb Feb 24 '21 at 21:10
  • When I run node client.js in powershell, I don't get any response – cans Feb 24 '21 at 22:27
  • error code does not appear – cans Feb 24 '21 at 22:27
  • As @hardillb mentioned you need to move the `client.subscribe('new-user');` into the `client.on('connect...` block. With this change (all on one machine and using `mqtt.connect('mqtt://localhost:1883')`) this works fine for me. – Brits Feb 25 '21 at 00:42

0 Answers0