在Express.js项目中使用Socket.io

时间:2016-01-04 17:36:01

标签: node.js express socket.io mean-stack

我正在使用Node.js,Express和Socket.io制作一些单页面Web应用程序。 我想显示工作如何进入浏览器。在IDE中,有控制台,所以我可以在控制台窗口中检查程序进程。就像,我想向浏览器展示这些过程。我想要的只是“排放”。

当我在app.js文件中使用socket.io时,没有问题。但这对我来说是有限的。我希望在运行时实时显示多个句子。我如何在app.js中使用socket.io而不是controller.js?我这篇文章是Use socket.io in controllers,但我无法理解。请帮我一个简单的解决方案。

app.js

var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);

module.exports.io = io;
...

controller.js

var io = require('./app').io;
// some task
console.log('Task is done!'); // it would be seen in console window
io.sockets.emit('Task is done!'); // Also I want to display it to broswer

结果(错误)

TypeError: Cannot read property 'sockets' of undefined

编辑2 ---

Follwoing Ashley B 的评论,我的编码是这样的。

controller.js

module.exports.respond = function(socket_io) {
    socket_io.emit('news', 'This is message from controller');
 };

app.js

var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var controller = require('./controller');
io.sockets.on('connection', controller.respond );

效果很好,但我想知道的是......当我想要几个socket_emit时,我该怎么办?我应该每次都打电话吗?如果你不明白。见下文:

//first task is done 
module.exports.respond = function(socket_io) {
    socket_io.emit('news', 'First task is done!');
 };

//second task is done 
module.exports.respond = function(socket_io) {
    socket_io.emit('news', 'Second task is done!');
 };

//third task is done 
module.exports.respond = function(socket_io) {
    socket_io.emit('news', 'Third task is done!');
 };

但这是错误的方式,对吗?只有最后一个api在app.js中实现。我的控制器中有很多console.log,我想将其转换为socket.emit我该怎么做?

1 个答案:

答案 0 :(得分:0)

我已经使用 socket.io nodejs事件对此进行了研究。这个想法是只处理app.js发出的套接字,并从控制器发出nodejs事件,这些事件将在app.js中捕获,然后由套接字发出。

app.js

const app = express();
const http = require('http');
const server = http.createServer(app);
const io = require('socket.io')(server);
const events = require('events');

io.on('connection', function(socket) {
    console.log("Someone has connected");
    var eventEmitter = new events.EventEmitter();
    eventEmitter.on("newEvent", (msg) => { // occurs when an event is thrown
        socket.emit("news", msg);
    });

    exports.emitter = eventEmitter; // to use the same instance
});

myController.js

const app = require('../app');    
.....

if (app.emitter) // Checking that the event is being received, it is only received if there is someone connected to the socket
    app.emitter.emit("newEvent", "First task is done!");    
.....

if (app.emitter)
    app.emitter.emit("newEvent", "Second task is done!");