我正在尝试通过socket.io在前端angularjs和后端节点之间进行通信。应用程序建立在Mean.io锅炉板上。套接字无法连接到后端。 这是我的代码
Angular.js
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('localhost:3000');
console.log('-------->' , socket)
socket.emit('new', { data: 'asd' });
socket.on('hi', function (data) {
alert('socket connected hi called');
console.log('===================== ============== data',data);
});
socket.on('broadcast', function (data) {
console.log('===================== ============== data',data);
});
</script>
Node.js的
MeanStarter.register(function (app, users, system, database, http) {
var io = require('./server/config/socketio')(http);
io.on('connection', function (socket) {
console.log(chalk.orange('------------------------ > a user connected'));
socket.emit('hi', { data: 'hello' });
socket.on('new', function (data) {
console.log(chalk.orange('=======> hello'));
})
});
app.set('views', path.join(__dirname, '/server/views'))
MeanStarter.routes(app, database);
MeanStarter.angularDependencies(['mean.system', 'mean.users',
'ui.bootstrap','ngFileUpload', 'angularjs-dropdown-multiselect',
'angularMoment','mwl.calendar'])
return MeanStarter
})
./服务器/配置/ socketio
'use strict';
var config = require('meanio').loadConfig(),
cookie = require('cookie'),
cookieParser = require('cookie-parser'),
socketio = require('socket.io'),
chalk = require('chalk');
module.exports = function(http) {
var io = socketio.listen(http);
// console.log( chalk.green('Socket Io conf',io));
io.use(function(socket, next) {
var data = socket.request;
if (!data.headers.cookie) {
return next(new Error('No cookie transmitted.'));
}
var parsedCookie = cookie.parse(data.headers.cookie);
var sessionID = parsedCookie[config.sessionName];
var parsedSessionID =
cookieParser.signedCookie(parsedCookie[config.sessionName],
config.sessionSecret);
if (sessionID === parsedSessionID) {
return next(new Error('Cookie is invalid.'));
}
console.log( chalk.green('Socket Io conf'));
next();
});
return io;
};
这是我的浏览器回复pic