Reputation: 3616
I'm testing Socket.io in a basic app, but io.sockets.emit
does not seem to be working as expected. Below is my relevant server-side code, Angular socket service, and controller. When I run this code only the current connection sees the console.log statement. Based on io.sockets.emit
I would have expected the opposite (every OTHER user sees the message logged upon connection of another user).
server.js:
var express = require('express');
var app = express();
var port = process.env.PORT || 8000;
var io = require('socket.io').listen(app.listen(port));
io.on('connection', function(socket){
io.sockets.emit('connect', {data: 'hey there!'});
});
console.log('Connected on port ' + port);
exports = module.exports = app;
socket.service.js:
angular
.module('app')
.factory('socketService', function ($rootScope) {
var socket = io.connect();
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
})
}
};
});
main.controller.js:
angular
.module('app')
.controller('MainController', MainController);
MainController.$inject = ['socketService'];
function MainController(socketService) {
var vm = this;
socketService.on('connect', function(data) {
console.log('connection identified');
});
}
Upvotes: 2
Views: 1555
Reputation: 2427
The problem is that connect
is a socket.io event that gets fired upon successful connection
Instead try using this on the server
io.sockets.emit('connect message', {data: 'hey there!'});
and this on the client
socketService.on('connect message', function(data) {
console.log('connection identified');
});
Upvotes: 2