Socket.io - 在 node.js 中的单独文件中监听事件 [英] Socket.io - listen events in separate files in node.js

查看:25
本文介绍了Socket.io - 在 node.js 中的单独文件中监听事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我的想法是:

File1.js

 io.sockets.on('connection', function (socket) {
      socket.on('file1Event', function () {
           //logic
      });
 });

File2.js

 io.sockets.on('connection', function (socket) {
      socket.on('file2Event', function () {
           //logic
      });
 });

此代码用于节点服务器,此代码会出现问题吗?

This code it's for a node server, I will have problems it this code?

推荐答案

不用,只需使用相同的io"对象.

Nope, just use the same "io" object.

File1.js

exports = module.exports = function(io){
  io.sockets.on('connection', function (socket) {
    socket.on('file1Event', function () {
      console.log('file1Event triggered');
    });
  });
}

File2.js

exports = module.exports = function(io){
  io.sockets.on('connection', function (socket) {
    socket.on('file2Event', function () {
      console.log('file2Event triggered');
    });
  });
}

app.js

var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')
  , file1 = require('./File1')(io)
  , file2 = require('./File2')(io)

app.listen(3000);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

index.html

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');
  socket.emit('file1Event');  // 'file1Event triggered' will be shown
  socket.emit('file2Event');  // 'file2Event triggered' will be shown
</script>

这篇关于Socket.io - 在 node.js 中的单独文件中监听事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆