private chat with socket.io
- First add user in chat room so that will easy to find a user in your private chat room
Your client side code for join private room
<input type="text" class="form-control" id="user_email" placeholder="user_email" /> <button text="join room" class="btn btn-primary btn-block" onclick="a();"> Join Room</button>
your javascript code in client side
function a(){ io.emit('privatechatroom', {email:document.getElementById('user_email').value}); }
your server side code to add user in your room
socket.on('privatechatroom',function(data){ socket.join(data.email); io.emit('res',{mes:"you are added"}) });
now u can send private message to that person that is recently addedd to this room client side
function b() {
io.emit('sendmail', { email: document.getElementById('sender_mail').value, message: document.getElementById('message').value });
$('#message').val('');
}
/*serverside code*/
socket.on('sendmail', function (data) {
io.sockets.in(data.email).emit('new_msg', { msg: data.message });
console.log(data.email);
});