Reputation: 243
I'm new to socket.io so I'm following the steps of this tutorial here
I'm trying to send a value from client to server, then make some calculations and send the new value to another view of the client. This is my code so far:
server.js
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket){
socket.on('fromClient', function(data){
console.log(data);
//calculations will be here, not relevant
socket.emit('fromServer', data);
});
// socket.send(req.query.gid);
socket.on('disconnect', function () {
});
});
client.js (the part that should receive the 'fromServer' emit, this is an angular controller)
var socket = io();
socket.on('fromServer', function(data){
console.log(data);
});
I know the 'fromClient' side is working cause it does print the value of data, but it doesn't print the 'fromServer' value. I'm not sure if the problem here is that the socket.emit inside socket.on is never called (server) or maybe the socket.on('fromServer') is not working(client).
For the record, I did another test and it did work, but it was only with express. On the other hand, I tried to use socket.send and socket.emit outside of the socket.on in my project and it worked, so I'm not sure if it has something to do with angular, it's the io.on('connection') event, or it's just the nesting.
Upvotes: 3
Views: 6043
Reputation: 41
When you use socket event inside the same socket, always call the event by io. I had used this in my project and it was working
Answer is io.emit(...)
var io = require('socket.io')(strapi.server);
io.on('connection', async function(socket) {
socket.on('getQuestionNext', (data)=>{
io.emit('question', {message : 1})
})
}
Upvotes: 4
Reputation: 243
Looks like nobody want to answer any of my questions...
It was the socket.emit, looks like it doesn't send it to everyone else but to the same client, that's why I was able to see it in the test (which had one view) but not in my real project.
The answer is io.sockets.emit(...)
Upvotes: 10