我在基本应用中测试Socket.io,但io.sockets.emit
似乎没有按预期工作。下面是我的相关服务器端代码,Angular套接字服务和控制器。当我运行此代码时,只有当前连接才能看到console.log语句。基于io.sockets.emit
,我原本期望相反(每个OTHER用户都会看到在连接另一个用户时记录的消息)。
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');
});
}
答案 0 :(得分:2)
问题是connect
是一个socket.io事件,在成功连接时被触发
而是尝试在服务器上使用它
io.sockets.emit('connect message', {data: 'hey there!'});
并在客户端上
socketService.on('connect message', function(data) {
console.log('connection identified');
});