Reputation: 2474
I am trying to get new connected user list in admin.html
server.js
app.get('/', function(req, res){
res.sendfile('client.html');
});
app.get('/admin', function(req, res){
res.sendfile('admin.html');
});
io.on('connection', function(socket){
socket.on('login', function(msg){
socket.emit('notification', 'new user joined');
});
socket.on('notification', function(msg){
console.log(msg);
});
});
Here I can try emit notification event from login event but it did not print anything in console, login event get trigger from client.html.
When I try this from client.html
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
$('form').submit(function(){
var a= $('#username').val();
var b= $('#usermail').val();
var c= $('#reason').val()
socket.emit('login',{username:a,usermail:b,reason:c});
socket.emit('notification','new user joined');
});
</script>
login event only get emit, notification does not work, when I run with notification event alone while it is working.
note: Suppose if I do from admin.html, I need set time looping for continuously check whether the new user have added or not. That is why I am looking automatically trigger the event while user connected.
please advice me how to achieve this?
Upvotes: 1
Views: 1132
Reputation: 1313
Try this:
io.on('connection', function(socket){
socket.on('login', function(msg){
socket.broadcast.emit('notification', 'new user joined');
console.log(msg);
});
});
The code of socket.on('notification', ...)
on server doesn't work because it is server that has emitted notification
Upvotes: 0
Reputation: 3766
Use
io.sockets.emit('notification', '')
This will emit everyone. I guess you can catch that event in admin.html.
But if you think the data needs to be secure and you don't want to send everyone, you can use socket io rooms
.
In admin.html
//after socket connection
socket.emit('join_admin_room')
in your socket codes:
io.on('connection', function(socket){
socket.on('join_admin_room', function(){ //from admin.html
socket.join('admin'); //add this socket to admin room
})
socket.on('login', function(msg){ /from index.html
//this will go to sockets in admin room
io.to('admin').emit('notification') //to admin.html
});
});
More information: http://socket.io/docs/rooms-and-namespaces/
Upvotes: 1