node mqtt server not propagating publishings - javascript

in this sample project i am trying to subscribe to a channel and publish into it.
However i never get back the message sent to the broker.
This is the server:
const mqttServer = require("mqtt-server");
const servers = mqttServer(
{
mqtt: "tcp://localhost:1883",
mqttws: "ws://localhost:1884",
},
{
emitEvents: true, // default
},
client => {
console.log("client connected!");
// console.log(client)
client.connack({
returnCode: 0,
});
client.on("data", data => {
console.log("got data: ");
console.log(data);
client.puback({messageId:data.packetId, ...data})
});
client.on("error", err => {
console.log(err);
});
},
);
servers.listen(_ => {
console.log("listening!");
});
servers.close(_ => {
console.log("close!");
});
And this is the client:
const mqtt = require("mqtt");
const client = mqtt.connect("mqtt://localhost:1883");
client.on("connect", ack => {
console.log("connected!");
// console.log(ack);
client.subscribe("/test", err => {
console.log(err);
});
client.on("message", (topic, message) => {
console.log(topic);
// message is Buffer
console.log(message.toString());
});
setInterval(_ => {
client.publish("/test", "Hello mqtt");
}, 3000);
});
client.on("error", err => {
console.log(err);
});
Any thoughts on what am i missing?

Turns out that using aedes broker the scenario on the sample project worked just fine!

Related

Get unread gmail mails with imap

Hello I'm trying to iplement some basics Google Api features and I get some issues when I try to get the unread messages in the gmail mailbox. Here is my code:
require('dotenv').config();
const nodemailer = require('nodemailer')
const { google } = require('googleapis')
const Imap = require('imap');
const CLIENT_ID = process.env.GOOGLE_CLIENT_ID
const CLIENT_SECRET = process.env.GOOGLE_CLIENT_SECRET
const REDIRECT_URI = process.env.GOOGLE_REDIRECT_URL
const REFRESH_TOKEN = process.env.GOOGLE_REFRESH_TOKEN
const oauht2Client = new google.auth.OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI)
oauht2Client.setCredentials({refresh_token : REFRESH_TOKEN})
function newMessages(/*onNewEmailCallback*/) {
const imap = new Imap({
user: "mymail#gmail.com",
xoauth2: oauht2Client.getAccessToken(),
host: 'imap.gmail.com',
port: 993,
tls: true,
tlsOptions: {
rejectUnauthorized: false
}
});
function showError(error) {
console.error('Error:', error);
}
function showMessage(msg) {
onNewEmailCallback(msg.subject);
console.log(msg.subject);
}
imap.connect();
imap.once('ready', () => {
imap.openBox('INBOX', true, (err, box) => {
if (err) showError(err);
imap.on('mail', (numNewMsgs) => {
imap.search(['UNSEEN'], (err, results) => {
if (err) showError(err);
results.forEach((result) => {
const f = imap.fetch(result, { bodies: '' });
f.on('message', (msg) => {
msg.on('body', (stream, info) => {
let buffer = '';
stream.on('data', (chunk) => {
buffer += chunk.toString('utf8');
});
stream.on('end', () => {
showMessage(Imap.parseHeader(buffer));
});
});
});
});
});
});
});
});
imap.once('error', showError);
imap.once('end', () => {
console.log('Connection terminée');
});
return imap;
}
When I call it in the index.js I get the error
/home/.../node_modules/imap/lib/Connection.js:1804
return str.replace(RE_BACKSLASH, '\\\\').replace(RE_DBLQUOTE, '\\"');
^
TypeError: str.replace is not a function
at escape
I'm probably passing a bad argument during the imap connection but I don't really know which one and I don't find anything online. Help PLEASE
By the way I had a certificate issue that's why I add the tlsOptions property.
Here the full traceback of the error:
/home/lerou/B-DEV-500-COT-5-2-area-segnon.gnonlonfoun/Back-End/node_modules/imap/lib/Connection.js:1804
return str.replace(RE_BACKSLASH, '\\\\').replace(RE_DBLQUOTE, '\\"');
^
TypeError: str.replace is not a function
at escape (/home/lerou/B-DEV-500-COT-5-2-area-/Back-End/node_modules/imap/lib/Connection.js:1804:14)
at Connection.<anonymous> (/home/lerou/B-DEV-500-COT-5-2-area-/Back-End/node_modules/imap/lib/Connection.js:1672:24)
at Connection._resTagged (/home/lerou/B-DEV-500-COT-5-2-area-/Back-End/node_modules/imap/lib/Connection.js:1535:22)
at Parser.<anonymous> (/home/lerou/B-DEV-500-COT-5-2-area-/Back-End/node_modules/imap/lib/Connection.js:194:10)
at Parser.emit (node:events:512:28)
at Parser._resTagged (/home/lerou/B-DEV-500-COT-5-2-area-/Back-End/node_modules/imap/lib/Parser.js:175:10)
at Parser._parse (/home/lerou/B-DEV-500-COT-5-2-area-/Back-End/node_modules/imap/lib/Parser.js:139:16)
at Parser._tryread (/home/lerou/B-DEV-500-COT-5-2-area-/Back-End/node_modules/imap/lib/Parser.js:82:15)
at Parser._cbReadable (/home/lerou/B-DEV-500-COT-5-2-area-/Back-End/node_modules/imap/lib/Parser.js:53:12)
at TLSSocket.emit (node:events:512:28)

How to pass data from net.Socket.on to an outside variable or return it

I'm working with net in node.js and I'm sending packet to a server and listening to the response, but I can't manage to return it. Here's my code:
function packetsend (sockeT, packeT) {
var resp = null;
if(sockeT) {
sockeT.write(packeT);
sockeT.on('data', (data) => {
resp = data.toString()
})
}
return resp;
}
const socket = new net.Socket();
socket.connect({host: server, port: port}, function() {
console.log('Connected');
var packetRecv = packetsend(socket, 'some packet');
if (packetRecv === 'some') {
console.log("ok");
}
})
I don't understand why packetsend() function is not returning the updated resp variable, and sends undefined object instead. When I do console.log(data) inside the sockeT.on() I see that it receives data.
Try transforming your packetsend() function in an async function. Maybe it's not returning the resp because you return it before the event 'data' is invoked.
This is just an example of a possible implementation:
function packetsend (sockeT, packeT) {
return new Promise((resolve, reject) => {
if (sockeT) {
sockeT.write(packeT);
sockeT.on('data', (data) => {
resolve(data.toString());
});
//WARNING: I don't know this 'socketT' object, don't know if there is an 'error' event.
//but it's recommended to handle errors. This is just an example.
sockeT.on('error', (error) => {
reject(error);
});
}
else{
reject('Missing sockeT');
}
});
}
const socket = new net.Socket();
socket.connect({ host: server, port: port }, function () {
console.log('Connected');
packetsend(socket, 'some packet').then(packetRecv => {
console.log('Received data => '+ packetRecv);
if (packetRecv === 'some') {
console.log("ok");
}
}).catch(error => console.log(error));
})
Update: you can also use the async/await
const socket = new net.Socket();
socket.connect({ host: server, port: port }, async function () {
try {
console.log('Connected');
let packetRecv = await packetsend(socket, 'some packet');
console.log('Received data => '+ packetRecv);
if (packetRecv === 'some') {
console.log("ok");
}
}
catch (error) {
console.log(error);
}
});
Tips:
"promise" documentation
"eventEmitter" documentation
"async/await" documentation

socket connected but not emit the message

Client-Side:
the socket used in website, initially connected and socket id is generated, but when try to emit the message, unable to emit from client to server-side.
<script>
const socket = io("http://localhost:8080");
socket.on("connection",() => {
})
const socketTrigger = () => {
console.log("message")
socket.emit("message", "testing data")
}
</script>
Server Side:
io.on("connection", socket => {
socket.on("message", (data) => {
console.log("message", data)
})
socket.on("startBidding", isAdminPage => {
socket.broadcast.emit("startBiddingArray", isAdminPage);
socket.on("disconnect", () => {
console.log("Client disconnected");
});
});
})
You just assign a variable with an anonymous function, but you don't call it like: socketTrigger(); at the end of the script.

Simple peer and socket.io keeps sending back and forth requests 100s of times. Unable to establish signal connections

I am trying to establish a connection between the two different users on the server. Every time a users joins the room he gets the info about the socket.ids of other users in the room. What they try and do is the new user creates an initiator peer and sends a signal . Which the other peer accepts for some reason they both keep sending each other back and forth requests and no one access each other requests this is what is happening.
A picture of the backend console
createPeer = (userToSignal, callerId, stream) => {
console.log('create peer called', userToSignal);
const peer = new Peer({
initiator: true,
trickle: false,
stream: stream
})
peer.on('signal', signal => {
console.log('sending a signal to server')
this.socket.emit('sending signal', {
'userToSignal': userToSignal,
'callerId': callerId,
'signal': signal
});
});
return peer;
}
addPeer = (incomingSignal, callerId, stream) => {
console.log('Add peer called', callerId);
const peer = new Peer({
initiator: false,
trickle: false,
stream: stream
});
peer.signal(JSON.stringify(incomingSignal));
peer.on('signal', signal =>{
console.log('returning a signal to : ', callerId)
this.socket.emit('returning signal', {
'signal': signal,
'callerId': callerId
});
});
return peer;
}
joinCall = () => {
navigator.mediaDevices.getUserMedia({ video: false, audio: true }).then(stream => {
console.log(this.socket.id);
this.socket.emit('join call', this.state.id, this.state.userName);
console.log('Join Call Called')
this.socket.on('all users', (usersInThisRoom) => {
console.log('all users ', usersInThisRoom);
const peers = [];
usersInThisRoom.forEach(user => {
console.log('for each called')
const peer = this.createPeer(user['id'], this.socket.id, stream);
peers.push({
'peerId' : user['id'],
'peer': peer
})
});
this.peersRefs = peers;
this.setState({peersRefs : this.peersRefs});
});
this.socket.on('user joined', payload => {
console.log('new user has joined', payload['callerId']);
const peer = this.addPeer(payload['signal'], payload['callerId'], stream);
this.peersRefs.push({
'peerId': payload['callerId'],
'peer': peer
})
this.setState({'peersRefs': this.peersRefs});
});
this.socket.on('receiving returned signal', payload => {
console.log('returned signal recieved ', payload.id)
const peerToSignal = this.peersRefs.find(peer => peer['peerId'] === payload.id)
peerToSignal['peer'].signal(JSON.stringify(payload.signal));
});
});
console.log('joining')
}
This is my front end code ^^
// Changes start
socket.on('join call', (roomId, name) => {
console.log('New User ', name)
SessionModel.findById(roomId, (err, session, callback) => {
if (err) throw err;
let users = session.usersInCall;
if (users.length === 10) {
return;
}
let userObject = { 'id' : socket.id, 'name' : name};
users.push(userObject);
SessionModel.findOneAndUpdate({_id: roomId}, {usersInCall: users}, {
new: true
},
(err) => {
if (err) throw err
});
const usersInThisRoom = users.filter(user => {
return user['id'] !== socket.id;
});
console.log(usersInThisRoom);
socket.emit("all users", usersInThisRoom);
})
})
socket.on('sending signal', payload => {
console.log('Sending Signal',payload['userToSignal'] );
io.to(payload['userToSignal']).emit('user joined', {
'signal': payload['signal'],
'callerId': payload['callerId']
});
})
socket.on('returning signal', payload => {
console.log('forwarding signal ',payload['callerId'])
io.to(payload['callerId']).emit('receiving returned signal', {
'signal' : payload['signal'],
'id': socket.id
});
})
This is my back end code ^^^
Try putting all ur socketio listners inside useEffect
Looks like you have created an infinite loop. Form the backend logs is
"forwarding signal ......" should have only be printed once. As the client socket is emitting the event returning signal twice.
Adding the client console logs would have helped in debugging.

Unable to broadcast multiple messages on socket io

I'm writing a program where I want to broadcast messages using socket IO. This is for a chat interface.
Here is my code
socket.on('send-chatMessage', message => {
var gotNewMsg = false;
sendChatMessage(message, chatMessagesJSON, function (resp, err) {
console.log('resp from send chat --->');
console.log(JSON.stringify(resp));
console.log('err');
console.log(err);
gotNewMsg = true;
socket.broadcast.emit('chat-message', {
message: message,
name: users[socket.id]
});
if (gotNewMsg) {
buildChatResponse(chatMessagesJSON, function (resp, err) {
console.log('resp from send chat');
console.log(JSON.stringify(resp));
console.log('err');
console.log(err);
socket.broadcast.emit('chat-message', {
message: JSON.stringify(resp.messages[0].type),
name: 'Agent'
});
});
}
})
});
Here My first
socket.broadcast.emit('chat-message', {
message: message,
name: users[socket.id]
});
is working fine but my second one
if (gotNewMsg) {
buildChatResponse(chatMessagesJSON, function (resp, err) {
console.log('resp from send chat');
console.log(JSON.stringify(resp));
console.log('err');
console.log(err);
socket.broadcast.emit('chat-message', {
message: JSON.stringify(resp.messages[0].type),
name: 'Agent'
});
});
}
is not working as expected. I'm able to enter the if and also print the result. The only thing failing is broadcasting.
Here is my broadcast handlers.
socket.on('chat-message', data => {
appendMessage(`${data.name}: ${data.message}`);
})
function appendMessage(message) {
const messageElement = document.createElement('div');
messageElement.innerText = message;
messageContainer.append(messageElement);
};
please let me know where am I going wrong.

Categories

Resources