Hi I'm building a web app that updates the user via socket.io how many tasks users have created on the website. I'm using socket.emit on the node.js side that will send a message to the angularjs client everytime a client creates a new task. However the codes doesn't execute, specifically the code inside this block in the node.js file:
console.log('a');
io.sockets.on('connection', function(socket) {
console.log('b');
io.sockets.emit('send', statinfo);
});
console.log('c');
When I look at the console I see "a" and "c" but not "b", as "b" is in that block of code that doesn't execute.
Here the rest of my code:
nodeapp.js (retrieves the numbers of tasks on the website)
app.post('/api/addtasks',function(req, res){
/*code to add tasks above*/
Stat.update(
{_id: statid},
{$inc: {'quantity': 1}},
function(err) {
console.log('test');
Stat.find({}, function(err, docs2) {
var statinfo = docs2;
io.sockets.on('connection', function(socket) {
io.sockets.emit('send', statinfo);
});
});
});
});
First, you don't want your socket.io events inside of a post request. First declare the connection and emits that happens on connection, and when inside post just do io.emit('event', functionName);
. I've done an example below on how you could structure socket.io-code.
As of now, your code reads like this: When the API posts, start the socket.io listening for a client connection. That's probably not what you want.
Have you started your server before trying to listen to socket.io events? How are your variables declared?
I've just tried this and it works, so maybe compare your own code to this.
server/app.js
// app.js
// this is basically just the example on https://socket.io docs
'use strict';
var app = require('http').createServer(handler);
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(8000);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
// start sending once client connects
io.on('connection', function (socket) {
console.log('Socket connected to client.');
// emits the string 'Yay!'
socket.emit('emitting', 'Yay!');
// logs the data that's emitted from client when they receive 'emitting'
socket.on('received', function (data) {
console.log(data);
});
});
// your api code should go here
client/index.html:
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
// listen to your server connection
var socket = io('localhost:8000');
// listen for the 'emitting' event, log data, emit new event 'received' back to server
socket.on('emitting', function (data) {
console.log(data);
socket.emit('received', 'thanks!');
});
</script>
</body>