我遇到了angularJS + node + socketio的问题。在我的应用程序中,可以通过socket.emit('enteredUsername','Guest')将数据从客户端发送到服务器;就像在controlls.js中一样。但它从服务器到客户端都不起作用。服务器收到'enteredUsername'后,他应该发回'UsernameOk'。但他没有...或者他发送它,但控制器没有收到它。有什么问题,因为我有多个控制器吗?
有人有想法吗?
EDIT1:
好的,在服务器端使用io.sockets.emit('enteredUsername', username)
代替socket.emit('enteredUsername', username)
修复了它。
server.js
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
app.use(express.static(__dirname + '/public'));
io.sockets.on('connection', function(socket) {
console.log('client connected!');
socket.on('enteredUsername', function(data) {
console.log('Username: ' + data);
socket.broadcast.emit('UsernameOk', data);
socket.emit('UsernameOk', data);
});
});
server.listen(1337);
services.js
angular.module('myApp.services', [])
.factory('socket', 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);
}
});
});
}
};
});
controllers.js
angular.module('myApp.controllers', [])
.controller('usernameCtrl', ['$scope', 'socket', function($scope, socket) {
$scope.username = 'guest';
$scope.EnteredUsername = function() {
var username = $scope.username;
socket.emit('enteredUsername', username);
}
socket.on('UsernameOk', function(data) {
console.log('Client-Get: UsernameOk -> ' + data);
});
}]);