Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

javascript - Socket.io - listen events in separate files in node.js

For example my idea is:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...