Socket.IO triggering request every second - javascript

I wonder how to stop socketio to trigger request every second. Here is my back and front end code:
io.on('connection', (socket) => {
console.log(`a user connected`)
socket.on('join', (data) => {
socket.broadcast.emit(
'player action',
`${data.name} has join the table`
)
console.log('user', `${data.name} has joined `)
console.log('data player: ', data)
})
socket.on('quit', (data) => {
socket.broadcast.emit('player action', `${data.name} has left`)
console.log(`user ${data.name} has left`)
})
socket.on('disconnect', () => {
console.log('a user quit')
})
})
on the client side there is only that:
const socket = io()

Related

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.

Firebase functions: send multiple notifications based on array elements

Its possible for me to send a notification to the reciever: idTo which is a string in the database. However, is it possible to use the array-field instead?: participants and send a notification to everyone in the array?
I store my users with their respective tokens at this path in firebase: Users->{userId}:
I've tried changing:
const idTo = doc.idTo
admin.firestore().collection('users').where('uid', '==', idTo).get().then(querySnapshot => {
to:
const participants = doc.participants
admin.firestore().collection('users').where('uid', 'arrayContains', participants).get().then(querySnapshot => {
Full code:
exports.sendNotification = functions.firestore
.document('messages/{roomId1}/room/{message}/message/{messageId}')
.onCreate((snap, context) => {
console.log('----------------start function--------------------')
const doc = snap.data()
console.log(doc)
const idFrom = doc.idFrom
const idTo = doc.idTo
const contentMessage = doc.message
// Get push token user to (receive)
admin.firestore().collection('users').where('uid', '==', idTo).get().then(querySnapshot => {
querySnapshot.forEach(userTo => {
console.log(`Found user to: ${userTo.data().uid}`)
if (userTo.data().pushToken) {
// Get info user from (sent)
admin.firestore().collection('users').where('uid', '==', idFrom).get().then(querySnapshot2 => {
querySnapshot2.forEach(userFrom => {
console.log(`Found user from: ${userFrom.data().uid}`)
const payload = {
notification: {
title: `${userFrom.data().name}`,
body: contentMessage,
badge: '1',
sound: 'default',
clickAction: 'FLUTTER_NOTIFICATION_CLICK',
// badge: '1'
},
data: {
title: '',
content: '',
image: '',
uploader: '',
type: 'chat',
},
}
// Let push to the target device
admin.messaging().sendToDevice(userTo.data().pushToken, payload).then(response => {
return console.log('Successfully sent message:', response)
}).catch(error => {
console.log('Error sending message:', error)
})
})
return console.log('failed')
}).catch(error => {
console.log('Error sending message:', error)
})
} else {
console.log('Can not find pushToken target user')
}
})
return console.log('error: invalid path')
}).catch(error => {
console.log('Error sending message:', error)
})
return null
})
I'm thinking maybe I need to loop over the array for each of the users and somehow execute the push notification. Any ideas are welcome
var messageToSend=req.body.messageToSend;
var message = { //this may vary according to the message type (single recipient, multicast, topic, et cetera)
registration_ids:regTokens , // Id List if more then one recipent
//to : regTokens, //use if One recipient
data: { //This is only optional, you can send any data
score: '',
time: ''
},
notification:{
body : messageToSend
}
};
console.log(message);
fcm.send(message, function(err, response){
if (err) {
console.log("Something has gone wrong!",err);
} else {
console.log("Successfully sent with response: ", response);
}
});

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.

node mqtt server not propagating publishings

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!

High Delay in FCM when sent through Firebase Functions

I'm trying to send FCM using Firebase Functions, This is the code I'm using
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
admin.firestore().settings({
timestampsInSnapshots: true
});
var token = 'token_value';
var sender = 'sender_value';
var reciever = 'reciever_value';
var message = 'message_value';
var payload ='payload_value';
var db = admin.firestore();
exports.sendFollowerNotification =
functions.database.ref('/m/{messageid}')
.onCreate((snapshot, context) => {
console.log('v21');
message = context.params.messageid;
console.log('Message Id:', message);
reciever = snapshot.val().r;
console.log('Message reciever: ', reciever);
sender = snapshot.val().s;
console.log('Message sender: ', sender);
payload = {
data: {
id: `${message}`,
sender: `${sender}`
}
};
console.log('Payload Created');
var tokenRef = db.collection(reciever).doc('t');
console.log('Fetching Token');
tokenRef.get()
.then(doc => {
console.log('Fetching Token started');
if (!doc.exists) {
console.log('Token doesnt exist ');
} else {
token = doc.data().v;
console.log('Token data:', token);
}
console.log('End Then');
return token;
})
.catch(err => {
console.log('Error getting token', err);
}).then((token) => {
console.log('Sending FCM now');
admin.messaging().sendToDevice(token,payload);
return console.log('Successfully sent message:');
})
.catch((error) => {
console.log('Error sending message:', error);
});
})
The problem is that FCM is received with huge delay(about 40s), however fcm sent from Firebase Console is received almost immediately (about 2-3s).
Since I am an android developer and have no experience of Node.js, I believe that something is wrong with JS code. Help me by telling whats wrong or possible workaround.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
admin.firestore().settings({
timestampsInSnapshots: true
});
var db = admin.firestore();
function debugLogger(msg) {
// comment out to disable logging
console.log(msg);
}
function errLogger(err) {
console.log(err);
}
exports.sendFollowerNotification =
functions.database.ref('/m/{messageid}')
.onCreate((snapshot, context) => {
debugLogger('v23_stackoverflow');
const message = context.params.messageid;
debugLogger(`Message Id: ${message}`);
const reciever = snapshot.val().r;
debugLogger(`Message reciever: ${reciever}`);
const sender = snapshot.val().s;
debugLogger(`Message sender: ${sender}`);
const payload = {
data: {
id: `${message}`,
sender: `${sender}`
}
};
debugLogger('Payload Created');
let tokenRef = db.collection(reciever).doc('t');
debugLogger('Fetching Token');
return tokenRef.get()
.then(doc => {
debugLogger('Fetching Token started');
if (!doc.exists)
throw new Error("Token doesnt exist");
let token = doc.data().v;
debugLogger(`Token data: ${token}`);
return token;
})
.then(token => {
debugLogger('Sending FCM now');
return admin.messaging().sendToDevice(token, payload);
})
.then(() => {
debugLogger('Successfully sent message!');
return null;
})
.catch(err => {
errLogger(err);
})
})

Categories

Resources