I built mosquitto on CentOS7 and a node.js client based on mqtt.js,installing with
yum install mosquitto mosquitto-clients
The local test
> mosquitto_sub -h localhost -t test
> mosquitto_pub -h localhost -t test -m "hello world"
works fine, but when I ran:
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://192.168.1.70')
client.on('connect', function () {
client.subscribe('presence')
client.publish('presence', 'Hello mqtt')
})
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
})
I got Error: Connection refused: Not authorized
The mosquitto.conf is like:
pid_file /var/run/mosquitto.pid
persistence true
persistence_location /var/lib/mosquitto/
log_dest file /var/log/mosquitto/mosquitto.log
allow_anonymous true
and I use systemctl restart mosquitto to restart it several time, which doesn't help. The firewall is down and log file stays empty.
A screenshot on status:
Can anyone help please?
UPDATE:
It turns out that the mosquitto service is somehow broken as the status shows Active: active (exited).
I use mosquitto -p 1884 -v cmd to run another mosquitto process on port 1884, it works fine. Then I try to reload the conf using
> /etc/init.d/mosquitto reload. It gives me
Reloading mosquitto configuration (via systemctl): Job for mosquitto.service invalid.
[FAILED]
So there IS something wrong with mosquitto service.
Not a final solution but I manage to fix this by remove-reboot-install process, the status went green as follow:
SOLUTION
I managed to find out the reason it doesn't work. I've installed rabbitmq on my server, it uses its "rabbitmq_mqtt" which consumes port 1883. Reassigning a port will solve this problem.
I managed to find out the reason. I've installed rabbitmq on my server, it uses its "rabbitmq_mqtt" which consumes port 1883. Reassigning a port will solve this problem. The problem is simple, but yeah, the CLI should have given me more information.
You need to add the authorize information to mqtt connect method.Just like this.
var client=mqtt.connect("ws://192.168.1.1", {
username: "yourUsername",
password: "yourPassword"
}
Add the Authorization details for the client to connect
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://192.168.1.70', {
username: '<username>',
password: '<password>'
});
client.on('connect', function () {
client.subscribe('presence')
client.publish('presence', 'Hello mqtt')
})
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
})
Related
On visiting local host 3000 I get Cannot GET / before using postman.
during the process of sending POST request in postman to the local host my program fails and I get this Error
`node:internal/process/promises:288
triggerUncaughtException(err, true /* fromPromise */);
^
Error: connect ECONNREFUSED ::1:5672
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1487:16) {
errno: -61,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '::1',
port: 5672`
config.js
----------
module.exports = {
rabbitMQ: {
url: "amqp://localhost",
exchangeName: "logExchange",
},
};
Producer.js
-----------
const amqp = require("amqplib");
const config = require("./config");
//step 1 : Connect to the rabbitmq server
//step 2 : Create a new channel on that connection
//step 3 : Create the exchange
//step 4 : Publish the message to the exchange with a routing key
class Producer {
channel;
async createChannel() {
const connection = await amqp.connect(config.rabbitMQ.url);
this.channel = await connection.createChannel();
}
async publishMessage(routingKey, message) {
if (!this.channel) {
await this.createChannel();
}
const exchangeName = config.rabbitMQ.exchangeName;
await this.channel.assertExchange(exchangeName, "direct");
const logDetails = {
logType: routingKey,
message: message,
dateTime: new Date(),
};
await this.channel.publish(
exchangeName,
routingKey,
Buffer.from(JSON.stringify(logDetails))
);
console.log(
`The new ${routingKey} log is sent to exchange ${exchangeName}`
);
}
}
module.exports = Producer;
Server.js
----------
`const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const Producer = require("./producer");
const producer = new Producer();
app.use(bodyParser.json("application/json"));
app.post("/sendLog", async (req, res, next) => {
await producer.publishMessage(req.body.logType, req.body.message);
res.send();
});
app.listen(3000, () => {
console.log("Server started...");
});`
I am a Junior Intern ad was following along an youtube video by https://www.youtube.com/watch?v=igaVS0S1hA4 by Computerix to help me understand the concepts
I tried restarting the rabbitMQ and express server and running it on different ports but didnt solve the problem
This is Big Picture
Postman -> Express Server -> RabbitMQ -> node.js
#1 Postman send message to Express with Message Types and payload by POST call
#2 Express Server forward message to Rabbit MQ by publish
#3 RabbitMQ - push the messages into own message queue
#4 Each consumer received own message from RabbitMQ. It was binned before.
There are many complex options(order, priority) but in here talking about basic and simple model.
Steps
We needs following three steps.
#1 : Install
1.1 docker (easy way to container to run RabbitMQ)
1.2 node
1.3 demo source
git clone https://github.com/charbelh3/RabbitMQ-Logger-Example.git
File structure
1.4 install node library
At RabbitMQ-Logger-Example\infoMS directory
npm install amqplib
At RabbitMQ-Logger-Example\loggerMS directory
npm install amqplib express body-parser
At RabbitMQ-Logger-Example\warningAndErrorMS directory
npm install amqplib
1.5 Install Postman
1.6 Install Git Bash - I will using git bash terminal. It similar bash terminal in Linux - If you using Linux, skip this.
#2 : Binding
2.1 running RabbitMQ
Save this code as docker-compose.yml
version: "3.8"
services:
rabbitmq:
image: rabbitmq:management-alpine
container_name: 'rabbitmq'
ports:
- 5672:5672
- 15672:15672
volumes:
- ~/.docker-conf/rabbitmq/data/:/var/lib/rabbitmq/
- ~/.docker-conf/rabbitmq/log/:/var/log/rabbitmq
networks:
- rabbitmq_go_net
networks:
rabbitmq_go_net:
driver: bridge
Run it
docker compose up
If docker compose version 1.x
docker-compose up
Open your browser with this URL
http://localhost:15672/
2.2 Run express and all node.js
At RabbitMQ-Logger-Example\infoMS directory
node app.js
At RabbitMQ-Logger-Example\loggerMS directory
node server.js
At RabbitMQ-Logger-Example\warningAndErrorMS directory
node app.js
Now ready to go
#3 : Message
Run Postman,
#1 Make own collection
#2 Make Three requests
One of Request - Send Info Message
#1 Select POST method
#2 Enter URL
localhost:3000/sendLog
#3 Click Body Tab
#4 Select Raw radio button
#5 Enter message into body
{
"logType" : "Info",
"message" : "I am Info message"
}
#6 Select JSON
#7 Press Send Button
If you see , You are success!
Other two different type message is same content
Just difference is logType's value.
Send Warning Message Request
For Warning
{
"logType" : "Warning",
"message" : "I am Warning message"
}
Send Error Message Request
For Error
{
"logType" : "Error",
"message" : "I am Error message"
}
This is real screen all of things!
If you browser, RabbitMQ content, you found many things.
This is one of it for Info channel information.
If want to terminate RabbitMQ
CTRL+C
docker compose down
Enjoy RabbitMQ!
enter image description here
I am not able to connect my database and getting this problem when i run any api call in postman ,I have tried so many things but not able to get it out .
This is probably because
The MongoDB service isn't started.
Start MongoDB: sudo systemctl start mongod
Verify that MongoDB has started successfully: sudo systemctl status mongod
The port is already serving some service.
Find pid: lsof -i:27017
Kill pid: kill -9 pid
Your connection string is incorrect
mongoose.connect('mongodb://localhost:27017/myapp');
Your localhost is not configured to use mongoDB
const app=require("./app");
const dotenv=require("dotenv");
const connectDatabase=require("./config/database");
PORT=4000;
//Handling uncaught Exception(YouTube Wala Error)
process.on("uncaughtException",(err)=>{
console.log(`Error:${err.message}`);
console.log(`Shuting Down the server due to uncaught Exception`);
process.exit(1);
})
// config
// dotenv.config({path:"backend/config/config.env"});
//Connecting to database
connectDatabase();
const server=app.listen(PORT,()=>{
console.log(`server is running on http://localhost:${PORT}`);
})
//Unhandled Promise Rejection-> in case when we use mongo(using)
process.on("unhandledRejection",err=>{
console.log(`Error: ${err.message}`);
console.log(`Shuting Down the server due to Unhandled Promise Rejection`);
server.close(() =>{
process.exit(1);
})
})
I have the server running on port 8080, I can see the web interface...
When I try to run this example from command line, like this: node test.js (node version: 4.1.0), I get:
playground/rethink/node_modules/rethinkdb/node_modules/bluebird/js/main/async.js:43
fn = function () { throw arg; };
^
ReqlTimeoutError: Could not connect to localhost:8080, operation timed out.
Why?
I installed RethinkDB via Homebrew and I'm on Mavericks.
I assume you changed the port number in the demo code to 8080?
r.connect({ host: 'localhost', port: 28015 }, ...
don't do that.
Port 8080 is reserved for http administrative connections, while client driver connections go through port 28015. Leave it at port 28015 and try it again.
I've setup my slanger server correctly. It runs but when I connect from the browser it complains about the app key not being found? but my app_key and key are the same...
I send events like so in python
p = pusher.Pusher(app_id='mysite', key='mysite', secret='secretstuff', host='slanger.mysite.com', port='4567')
I run the slanger server like this:
slanger -k mysite -s secretstuff
Running Slanger v.0.4.0
Slanger API server listening on port 4567
Slanger WebSocket server listening on port 8080
This is what the browser outputs
WebSocket connection to
'wss://slanger.mysite.com:8080/app/mysite?protocol=7&client=js&version=2.2.3&flash=false'
failed: Error in connection establishment: net::ERR_CONNECTION_CLOSED
pusher.min.js:12 Pusher : Error :
{"type":"WebSocketError","error":{"type":"PusherError","data":{"code":4001,"message":"Could
not find app by key mysite. Perhaps you're connecting to the wrong
cluster."}}}
here's my JS code:
Pusher.host = 'slanger.mysite.com'
Pusher.app_id = 'mysite'
Pusher.ws_port = 8080
Pusher.wss_port = 8080
var pusher = new Pusher('mysite');
var channel = pusher.subscribe("test");
channel.bind('update', function (data) {
console.log(data.message);
});
It looks like you forgot to add wsHost config option.
I got the same issue as you, and this worked for me.
Following slanger documentation, you should do it like this:
Pusher.host = 'slanger.example.com'
Pusher.port = 4567
var pusher = new Pusher('#{Pusher.key}', {
wsHost: "0.0.0.0",
wsPort: "8080",
wssPort: "8080",
enabledTransports: ['ws', 'flash']
});
I'm writing an event-driven publish/subscribe application with NodeJS and Redis. I need an example of how to notify web clients when the data values in Redis change.
OLD only use a reference
Dependencies
uses express, socket.io, node_redis and last but not least the sample code from media fire.
Install node.js+npm(as non root)
First you should(if you have not done this yet) install node.js+npm in 30 seconds (the right way because you should NOT run npm as root):
echo 'export PATH=$HOME/local/bin:$PATH' >> ~/.bashrc
. ~/.bashrc
mkdir ~/local
mkdir ~/node-latest-install
cd ~/node-latest-install
curl http://nodejs.org/dist/node-latest.tar.gz | tar xz --strip-components=1
./configure --prefix=~/local
make install # ok, fine, this step probably takes more than 30 seconds...
curl http://npmjs.org/install.sh | sh
Install dependencies
After you installed node+npm you should install dependencies by issuing:
npm install express
npm install socket.io
npm install hiredis redis # hiredis to use c binding for redis => FAST :)
Download sample
You can download complete sample from mediafire.
Unzip package
unzip pbsb.zip # can also do via graphical interface if you prefer.
What's inside zip
./app.js
const PORT = 3000;
const HOST = 'localhost';
var express = require('express');
var app = module.exports = express.createServer();
app.use(express.staticProvider(__dirname + '/public'));
const redis = require('redis');
const client = redis.createClient();
const io = require('socket.io');
if (!module.parent) {
app.listen(PORT, HOST);
console.log("Express server listening on port %d", app.address().port)
const socket = io.listen(app);
socket.on('connection', function(client) {
const subscribe = redis.createClient();
subscribe.subscribe('pubsub'); // listen to messages from channel pubsub
subscribe.on("message", function(channel, message) {
client.send(message);
});
client.on('message', function(msg) {
});
client.on('disconnect', function() {
subscribe.quit();
});
});
}
./public/index.html
<html>
<head>
<title>PubSub</title>
<script src="/socket.io/socket.io.js"></script>
<script src="/javascripts/jquery-1.4.3.min.js"></script>
</head>
<body>
<div id="content"></div>
<script>
$(document).ready(function() {
var socket = new io.Socket('localhost', {port: 3000, rememberTransport: false/*, transports: ['xhr-polling']*/});
var content = $('#content');
socket.on('connect', function() {
});
socket.on('message', function(message){
content.prepend(message + '<br />');
}) ;
socket.on('disconnect', function() {
console.log('disconnected');
content.html("<b>Disconnected!</b>");
});
socket.connect();
});
</script>
</body>
</html>
Start server
cd pbsb
node app.js
Start browser
Best if you start google chrome(because of websockets support, but not necessary). Visit http://localhost:3000 to see sample(in the beginning you don't see anything but PubSub as title).
But on publish to channel pubsub you should see a message. Below we publish "Hello world!" to the browser.
From ./redis-cli
publish pubsub "Hello world!"
here's a simplified example without as many dependencies.
You do still need to npm install hiredis redis
The node JavaScript:
var redis = require("redis"),
client = redis.createClient();
client.subscribe("pubsub");
client.on("message", function(channel, message){
console.log(channel + ": " + message);
});
...put that in a pubsub.js file and run node pubsub.js
in redis-cli:
redis> publish pubsub "Hello Wonky!"
(integer) 1
which should display: pubsub: Hello Wonky! in the terminal running node!
Congrats!
Additional 4/23/2013: I also want to make note that when a client subscribes to a pub/sub channel it goes into subscriber mode and is limited to subscriber commands. You'll just need to create additional instances of redis clients. client1 = redis.createClient(), client2 = redis.createClient() so one can be in subscriber mode and the other can issue regular DB commands.
Complete Redis Pub/Sub Example (Real-time Chat using Hapi.js & Socket.io)
We were trying to understand Redis Publish/Subscribe ("Pub/Sub") and all the existing examples were either outdated, too simple or had no tests.
So we wrote a Complete Real-time Chat using Hapi.js + Socket.io + Redis Pub/Sub Example with End-to-End Tests!
https://github.com/dwyl/hapi-socketio-redis-chat-example
The Pub/Sub component is only a few lines of node.js code:
https://github.com/dwyl/hapi-socketio-redis-chat-example/blob/master/lib/chat.js#L33-L40
Rather than pasting it here (without any context) we encourage you to checkout/try the example.
We built it using Hapi.js but the chat.js file is de-coupled from Hapi and can easily be used with a basic node.js http server or express (etc.)
Handle redis errors to stop nodejs from exiting. You can do this by writing;
subcribe.on("error", function(){
//Deal with error
})
I think you get the exception because you are using the same client which is subscribed to publish messages. Create a separate client for publishing messages and that could solve your problem.
Check out acani-node on GitHub, especially the file acani-node-server.js. If these links are broken, look for acani-chat-server among acani's GitHub public repositories.
If you want to get this working with socket.io 0.7 AND an external webserver you need to change (besides the staticProvider -> static issue):
a) provide the domain name instead of localhost (i.e. var socket = io.connect('http://my.domain.com:3000'); ) in the index.html
b) change HOST in app.js (i.e. const HOST = 'my.domain.com'; )
c) and add sockets in line 37 of app.js (i.e. 'socket.sockets.on('connection', function(client) { …' )
Update to the code:
staticProvider
now renamed to
static
see migration guide
according to #alex solution. if you have an error like this one as per #tyler mention:
node.js:134
throw e; // process.nextTick error, or 'error'
event on first tick ^ Error: Redis connection to 127.0.0.1:6379 failed - ECONNREFUSED, Connection refused at Socket.
then you need to install Redis first. check this out:
http://redis.io/download