i am building a mobile app with ionic, i am using socket.io, i want to be able to send message to a particular user with an id, and not broadcast the message to everyone, the chat application is not a chat room style kind of app but a one on one chatting app like watsapp, i searched online but what i saw was not working, here is the code for the server side
const io = require('socket.io')(server);
io.on('connection', socket => {
console.log('New user connected');
socket.on('get_all_msg', data => {
DBConn.query(`SELECT * FROM chats WHERE rec_id = ? || send_id=?`, [data.id, data.id], (error, results, fields) => {
if (error) throw error;
io.to(data.id).emit('all_msg', results)
});
})
})
the id of the user i am chatting with is the data.id
, i tried using io.to(data.id).emit('all_msg', results)
but the user did not receive any message, pls what am i doing that is not right
Here's the client side code
this.socket.emit('get_all_msg', {id:this.contactInfo.id})
this.service.socket.fromEvent('all_msg').subscribe((data:any) => {
console.log(data)
})
I am using ngx-socket.io
in my ionic add
we need to map socket id to user id; we can solve this using redis but simple way i did was
actually socket io itself joins the current into a room with its id(socketio) itself; i was like, "why not join that socket into room with user_id"
backend side:
front end side:
when one user emits new-message event we can get the participent id's and can simply loop over their ids and emit an event
works with one to one and group chat!