要在不同的文件中使用 io 对象,我使用下面的方法。我似乎没有收到编译错误。所以 io 是在 users.js 文件中“定义”的。但我似乎没有发出任何事件。有没有人看到问题?
应用程序.js
var app = require('express')()
, server = require('http').createServer(app)
global = require('./global.js');
global.io = require('socket.io').listen(server);
global.io.configure(function () {
global.io.set("transports", ["xhr-polling"]);
global.io.set("polling duration", 10);
});
// express settings
require('./config/express')(app, config, passport)
require('./config/passport')(passport, config, env)
// Bootstrap routes
require('./config/routes')(app,passport)
var port = process.env.PORT || 3000
server.listen(port)
global.js
var Global = {
io : { }
};
module.exports = Global;
路由.js
var users = require('../app/controllers/users')
module.exports = function (app, passport) {
app.post('/incomingFake', users.getFake);
}
用户.js
var global = require('../../global.js')
exports.getFake = function(req, res){
global.io.sockets.on('connection', function(socket) {
socket.broadcast.emit('email', req.body);
});
User.findAndStoreEmail(senderEmail, email ,function(){
res.writeHead(200, {'content-type': 'text/plain'})
res.end('Message Received. Thanks!\r\n')
})
}
我尝试在前端的骨干集合中接收它
define([
'jquery',
'underscore',
'backbone',
'Email',
'marionette',
'socketio'
], function ($, _, Backbone, emailModel, Marionette, io) {
'use strict';
var Emails = Backbone.Collection.extend({
url : '/emails',
model : emailModel,
initialize : function() {
var socket = io.connect('http://localhost:3000');
socket.on('email', function (data) {
console.log("i got the socket connection");
console.log(data);
});
}
});
return Emails;
});
编辑:
我意识到了什么!我认为这可能对解决问题有很大帮助,我实际上收到了连接事件并且套接字发出了一些东西,但这一切都发生在页面加载时。我希望这个事件只发出'getFake'函数被调用