I'm following the tutorial provided here : http://www.davidado.com/2013/12/10/node-js-for-user-alert-push-notifications/ The goal is to allow someone to send a message to another user.
Node is installed and works. I also installed Socket.io.
When I run
node server.js
I have this error :
TypeError: undefined is not a function
at Socket.<anonymous> (/root/nodeapp/server.js:11:39)
The server.js (server side) is like this :
var io = require('socket.io').listen(5120);
io.sockets.on('connection', function (socket) {
socket.on('join_room', function (data) {
if (typeof socket !== 'undefined') {
// data.id should be set if user is logged in
if (typeof data.id !== 'undefined' && data.id > 0) {
// Check if socket is already in room
var roomlist = io.sockets.clients(data.id); // returns Socket instances of all clients in the room
var occupantSocket;
if (typeof roomlist[0] !== 'undefined') {
// Should only be one socket in a private room
occupantSocket = roomlist[0];
}
if (socket !== occupantSocket) {
// Socket hasn't joined before so join it now
socket.join(data.id);
}
} else {
// User ID isn't set so disconnect the socket
socket.disconnect();
}
}
});
socket.on('send_msg', function (data) {
if (typeof socket !== 'undefined') {
if (typeof data.id_sendee !== 'undefined' && data.id_sendee > 0) {
// Check if anyone is in the room before broadcasting
var roomlist = io.sockets.clients(data.id_sendee);
if (typeof roomlist[0] !== 'undefined') {
// Push alerts aren't that critical so use volatile
socket.broadcast.to(data.id_sendee).volatile.emit(
'newalert',
{sender: data.sender, msg: data.msg });
}
} else {
socket.disconnect();
}
}
});
});
console.log("Hello , just checking!");
Line 11 is this one :
var roomlist = io.sockets.clients(data.id); // returns Socket instances of all clients in the room
On the client side, the one receiving the message :
<html>
<head>
<title>Test Node</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdn.socket.io/socket.io-1.3.5.js"></script>
<script type="text/javascript">
var socket = io.connect('http://IPAdressofMyServer:5120');
socket.emit('join_room', { id: 234 });
// Listen for 'newalert' event from node server at server.js
socket.on('newalert', function (data) {
alert( data.msg + ' from ' + data.sender );
});
</script>
</head>
<body>
</body>
</html>
When I launch node server.js in my console, there is no error, but as soon as I refresh the client (with the code above), the error is triggered.
Any idea what the problem is ? thank you for your help !