我有一個server.js文件是這樣的:Node.JS + Socket.io,將套接字事件處理程序移動到外部模塊?
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('連接),功能( ){...})事件處理程序沒有被調用,它應該在客戶端連接時輸出一個console.log消息。我想將我的socket.io事件保存在我的主server.js文件之外,因爲它們會有很多,我想將它們分離到它們自己的模塊中。
嗨,這是我的錯誤。感謝您的回覆,我錯過了發送'連接'的客戶端代碼,woops :( –
將此添加到我的index.html中\t –