Implement unread messages - javascript

I am implementing a live chat.
Here is my server file.
io.on('connection', socket => {
socket.on('userConnect', async (room, user_id) => {
socket.join(room);
});
socket.on('send-chat-message', (room, sender_id, userMessage) => {
const message = new Message(room, sender_id, userMessage);
db.query(message.saveMessage());
socket.to(room).emit('chat-message', { message: userMessage, user: sender_id });
});
});
This is how I implemented the connection to the room and the connection for sending messages from the client.
How can I make a function that the user has not yet read the message?

Related

WebSocket is closed before the connection is established

i want to use jsonwebtoken, but after i've tried implement it, it gives me this error:WebSocket is closed before the connection is established.
I cant see whats wrong with the code. im not able to do anything on the localhost as it looses connection all the time.
Client
chat.js
const socket = io({
extraheaders: {
token : sessionStorage
}
});
Server
app.js
io.use((socket, next) => {
const {token}= socket.handshake.auth.headers;
if (token && token ===sessionStorage){
return next();
}
next(new Error('Pls login again'))
.on('connection', function(socket) {
console.log(token)
// Connection now authenticated to receive further events
socket.on('message', function(message) {
io.emit('message', message);
console.log(socket.handshake.auth.headers)
});
[![Localstorage][1]][1]
[1]: https://i.stack.imgur.com/YewlR.png

Callback Function in App.Listen in Nodejs after User Logs in

I am building an IOT app incorporating MQTT. My challenge is this :
The list of topics a user has subscribed to are saved to a MongoDB collection. Once the User logs into the app, this list of topics is available for operation. What I want to do is to create a function that starts running once the user has logged in and listens to any message on the subscribed topics and update device state which is also saved to the MongoDB collection.
Through this code, I can receive messages if I hard code the topics :
mongoose.connect(URI).then(res => {
console.log("Connected to DB")
const server = app.listen(3000, function () {
const client = mqtt.connect('mqtt://test.mosquitto.org')
// console.log("MQTT CLIENT : ", client)
client.on('connect', () => {
console.log('Connected')
})
client.subscribe(`62d7d71d65c27a/devices/62dd2208c4b`, () => {
console.log("Subscribe to topic 62d7d71d65c27a/devices/62dd2208c4b")
})
client.on('message', (topic, payload) => {
console.log(payload.toString())
})
const io = require('./socket').init(server)
})
}).catch(err => console.log(err))
How can I make a call back function to run with app.listen, which can be called once the user has logged in ?

Why is the client not receiving the socket.io broadcast (rooms)?

My client is not receiving the broadcast sent to the room. If I replace socket.to(roomName).emit('join', currentUser); with socket.emit('join', currentUser); the client receives the broadcast, but I'd like to use rooms here. Any help would be greatly appreciated.
app.js
// Game
app.get('/game', (req, res) => {
const cookies = req.cookies;
const currentUser = cookies['current_user'];
const roomName = cookies['room_name'];
if (roomName) {
res.render('pages/game', {
room: roomName
});
io.of('/game').on('connection', socket => {
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
socket.join(roomName);
socket.to(roomName).emit('join', currentUser);
});
} else {
res.redirect('/login');
}
});
game.ejs
const socket = io("/game");
socket.on('join', function(user) {
console.log(`${user} joined`);
});
Also, could I replace this:
if (roomName) {
// stuff
} else {
// other stuff
}
with this:
if (!roomName) {
// other stuff
return;
}
// stuff
According to the documentation, if you use socket.to('room').emit(...) instead of io.in('room').emit(...), it will be broadcasted to all sockets in the room except the sender. That's where your problem lies.
The reason socket.emit(...) works is because you're sending it directly and only to the sender.
This emit cheatsheet is quite useful to figure out which combinations of io/socket and to etc affect where messages get sent to.

How can i send data from a UDP server to a browser?

I try to make an application that receives from a third part application UDP packets.
I try to create a server UDP in NodeJS, but now when I receive the data I don't know how can I show it in a browser windows.
I explain better...my application receives data via udp in real time, the server processes them and should show them real time on a web page.
This is my code for UDP server in NodeJS:
const dgram = require('dgram');
const server = dgram.createSocket('udp4');
server.on('error', (err) => {
console.log(`server error:\n${err.stack}`);
server.close();
});
server.on('message', (msg, rinfo) => {
console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
console.log(` messaggio ricevuto ${msg}`);
});
server.on('listening', () => {
const address = server.address();
console.log(`server listening ${address.address}:${address.port}`);
});
server.bind({
adress:'127.0.0.1',
port:'41234'
});
// server listening address :41234
Thanks a lot for the reply
welcome to SO!
You could do something like below...
// Open a connection
var socket = new WebSocket('ws://localhost:41234/');
// When a connection is made
socket.onopen = function() {
console.log('Opened connection 🎉');
// send data to the server
var json = JSON.stringify({ message: 'Hello 👋' });
socket.send(json);
}
// When data is received
socket.onmessage = function(event) {
console.log(event.data);
}
// A connection could not be made
socket.onerror = function(event) {
console.log(event);
}
// A connection was closed
socket.onclose = function(code, reason) {
console.log(code, reason);
}
// Close the connection when the window is closed
window.addEventListener('beforeunload', function() {
socket.close();
});
This link should give you more info : https://www.sitepoint.com/real-time-apps-websockets-server-sent-events/ (above snippet is taken from this link)
You need a web server to send data to browser.
This link https://socket.io/get-started/chat will help you create a webserver.
You could send the message received on UDP port to the websocket as below
server.on('message', (msg, rinfo) => {
socket.emit('sendData', msg);
});

socket.io keep repeating fail request

I have strange issue. Basically the client will send a request i.e:delete chat, but Server will reject, since client is not authorized.
however, the client keep repeating the same request, even if I open new browser and load the same address. Both browser will keep requesting the previous action. my code looks something like this:
Client
socket.on(username, (res) => {
show(res.err)
})
socket.send({
type: "delete_chat",
username: username,
id: chat_id
})
Server:
io.sockets.on("connection", (socket) => {
socket.on("message", (data) => {
if(data.type === "delete_chat"){
Chat.delete(chatid, (err, res) => {
io.emit(username, {err:res}) //send error to username
});
}
})
})

Categories