Express.js包含来自另一个文件的套接字事件?

时间:2016-06-30 19:28:08

标签: javascript node.js sockets

我是新来表达并发现我的app.js变得有点拥挤。有没有办法可以把我的所有套接字事件,把它们放在文件夹中的另一个文件中,并将其包含在

io.sockets.on("connection", function(socket){
  //Require socket event file here
});

的  我试图采取以下措施: 的

 require('./mysockets')(server);

并在另一个文件中执行: 的

var io = require("socket.io");

// declare module constructor that is passed the http server to bind to
module.exports = function(server) {
     io.listen(server);
     //My code here
 };

我在这个例子中遗漏了什么吗?我添加了一个pastebin:http://pastebin.com/zvs8aMjN

这显示了我在上述操作时遇到的错误。

编辑:

添加了我的套接字事件以显示它的使用方式。我已经确认所有这些代码在我的app.js中直接运行时都有效,但是这个需求似乎打破了它。 的

  console.log("Client connection, no username");

    // ===============================================
    // DISCONNECTION
    // ===============================================
    socket.on('disconnect', function(data) {
      // Allows us to track if a unknown user has disconnected or if a known user has dosconnected
      if(!socket.username) {
        console.log("Client disconnected before username");
      } else {
        console.log("Player " + socket.username + " disconnected");
        serverFunctions.lobbyCheck();
        // Removes only one user
        allUsers.splice(allUsers.indexOf(socket.username), 1);
      }

      // Calls update usernames function
      serverFunctions.updateUsernames();
    });

    // ===============================================
    // NEW PLAYER LOGIC
    // ===============================================

    // Player has connected
    // Checks if username is already been used
    socket.on("new user", function(data, callback){
      // If it exists return false, else add it to array of allUsers
      if (allUsers.indexOf(data) != -1) {
        callback(false);
      } else {
        callback(true);
        socket.username = data;
        allUsers.push(socket.username);
        // Tells all active users which users are active
        serverFunctions.updateUsernames();
        console.log("Player " + socket.username + " connected");

        serverFunctions.lobbyCheck();
        // Calls theplayer check in order to push through the player names client side
        serverFunctions.playerCheck();
      }
    });

    // ===============================================
    // Game Start Logic
    // ===============================================

    // ===============================================
    // CHAT LOGIC
    // ===============================================

    // Broadcasts a message
    socket.on("send message", function(data){
      io.sockets.emit("new message", {msg: data, user: socket.username});
    });
});

这发生在我的socketconnection上面:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

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

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hjs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

1 个答案:

答案 0 :(得分:1)

在app.js中你得到io像这样的对象

var io = require('socket.io')(server);

现在您需要将此io对象传递给套接字模块,以便代码可以向此对象添加列表器。

在app.js中替换

require('./mysockets')(server);

require('./mysockets')(io);

因为您必须传递io个对象,而不是server对象。

mysockets.js档案中

module.exports = function(io) {
    io.sockets.on("connection", function(socket){
          // Broadcasts a message
          socket.on("send message", function(data){
             io.sockets.emit("new message", {msg: data, user: socket.username});
          });

        // other listeners will go here.
    });
};