im trying to build a private chat system in nativescript app using socketio and nodejs for the live chat feature.
this is the plugin i use https://github.com/triniwiz/nativescript-socketio/
It works well as a group chat, but i want to make it private. so i searched and saw io.sockets.in().emit
is what i'm supposed to use rather than io.emit()
this is what i tried
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
socket.on('privatechatroom', function(data){
socket.join(data.chatid, function () {
io.sockets.in(data.chatid).emit('joined', { mes: 'Joined chat room' + data.chatid });
socket.on('chat message', (data) => {
console.log('message: ' + data.message);
//io.emit('chat message', );
io.sockets.in(data.chatid).emit('chat message', { message: data.message, type: data.type, date: data.date, sender: data.sender });
});
socket.on('typing', (msg) => {
console.log('message: ' + msg);
io.sockets.in(msg).emit('typing', msg);
});
socket.on('notTyping', (msg) => {
console.log('message: ' + msg);
io.sockets.in(msg).emit('noTyping', msg);
});
});
});
});
On broswer, it works well for a private chat. but on my nativescript app, it doesnt work except i use io.emit()
rather than io.sockets.in()
first of all , you cant use socket.on(event...) in socket.join() section:
socket.on('privatechatroom', function(data){
socket.join(data.chatid, function () {
socket.in(data.chatid).emit('joined', { mes: 'Joined chat room' + data.chatid });
});
socket.on('chat message', (data) => {
console.log('message: ' + data.message);
//io.emit('chat message', );
socket.in(data.chatid).emit('chat message', { message: data.message, type: data.type, date: data.date, sender: data.sender });
});
socket.on('typing', (msg) => {
console.log('message: ' + msg);
socket.in(msg).emit('typing', msg);
});
socket.on('notTyping', (msg) => {
console.log('message: ' + msg);
socket.in(msg).emit('noTyping', msg);
});
});
when you join the socket client in a room you have to emmit your messages directly to that room with :
socket.to(chatid).emit('your event', {
foo:"bar"
});