我有一个像这样的server.js文件:
var express = require('express'),
app = express(),
server = require('http').createServer(app),
mongoose = require('mongoose'),
bodyParser = require('body-parser'),
apiRouter = require('./app/routes/api.js'),
io = require('socket.io')(server),
socketEvents = require('./app/modules/socketEvents.js')(io);
//Clears Node Console.
process.stdout.write('\033c');
console.log('Server starting!');
socketEvents.attachEventHandlers();
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use('/api', apiRouter);
app.use(express.static('public'));
app.use('*', function(req, res, next) {
//All requests return single page angular application.
res.sendFile(__dirname + '/public/index.html');
});
mongoose.connect('localhost', 'triviaattack', function(err) {
if (err) {
console.log('An error occured when connecting to the MongoDB Database');
throw err;
}
});
server.listen(1337);
和socketEvents.js
module.exports = function(io) {
return {
attachEventHandlers: function() {
io.on('connection', function(socket) {
console.log('client connected');
socket.on('joinMatchMaking', function(data) {
//Every time a player joins the matchmaking queue, check if a game can be created.
matchMakingQueue.push(data);
var matchedPlayers = [];
for (i = 0; i < matchMakingQueue.length; i++) {
switch (data.gameType) {
case '1v1':
matchedPlayers.push(matchMakingQueue[i].username);
if (matchedPlayers.length == 2) {
socket.emit('matchFound', {players: matchedPlayers});
}
console.log('user joined 1v1 queue');
case '2v2':
matchedPlayers.push(matchMakingQueue[i].username);
if (matchedPlayers.length == 4) {
socket.emit('matchFound', {players: matchedPlayers});
}
console.log('user joined 2v2 queue');
}
}
console.log(data.username + ' joined the ' + data.gameType + ' matchmaking queue');
console.log('users in queue: ' + matchMakingQueue.length);
});
socket.on('leaveMatchMaking', function(username) {
matchMakingQueue.splice(matchMakingQueue.indexOf(username), 1);
console.log(username + ' left matchmaking queue.');
console.log('users in queue: ' + matchMakingQueue.length);
});
});
console.log('events attached');
}
}
};
当我在浏览器中加载我的网站时,不会调用io.on('connection),function(){...})事件处理程序,每当客户端连接时都会输出console.log消息。我想将socket.io事件保存在我的主server.js文件之外,因为会有很多这样的事件,我想把它们分成自己的模块。
答案 0 :(得分:2)
你需要在html文件中有一些套接字代码才能连接..你也可以包含它吗?
答案 1 :(得分:1)
我是通过将所有套接字事件填充到中间件中来实现的:
var io = require('socket.io');
// listen stuff
var SocketEvents = require('./socket-events.js')(io);
io.use(SocketEvents);
...然后在socket-events.js
之类的内容:
module.exports = function(io) {
return function(socket, next) {
// do stuff
return next();
}
}
我应该补充一点,在这种情况下,on("connection")
监听器似乎没有必要,因为每个中间件功能都已在每个传入的套接字连接上执行。