我对 node.js 相当陌生,我发现随着项目规模的增长,将一个项目分成多个文件是相当复杂的。之前我有一个很大的文件,它既是一个文件服务器,也是一个多人 HTML5游戏的 Socket.IO 服务器。在理想情况下,我希望将文件服务器、 socket.IO 逻辑(从网络读取信息并将其写入带有时间戳的缓冲区,然后将其发送给所有其他参与者)和游戏逻辑分开。
使用 socket.io 中的第一个示例来演示我的问题,通常有两个文件。app.js
是服务器,index.html
被发送到客户端。
App.js:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(80);
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);
});
}
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
.html:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
为了分离文件服务器和游戏服务器逻辑,我需要在一个文件中定义函数“处理程序”,我需要一个使用 io.sockets.on ()回调的匿名函数在另一个文件中,我还需要第三个文件来成功地包含这两个文件。现在我尝试了以下方法:
Js:
var fileserver = require('./fileserver.js').start()
, gameserver = require('./gameserver.js').start(fileserver);
Js:
var app = require('http').createServer(handler),
fs = require('fs');
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);
});
}
module.exports = {
start: function() {
app.listen(80);
return app;
}
}
游戏服务器:
var io = require('socket.io');
function handler(socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
}
module.exports = {
start: function(fileserver) {
io.listen(fileserver).on('connection', handler);
}
}
这似乎可以工作(静态内容被正确地提供,当客户端连接时,控制台清楚地显示与 Socket.IO 的握手) ,尽管没有数据被发送。就好像从来没有实际调用 socket.sent ()和 socket.on ()一样。我甚至修改了处理程序()在 gameserver.js
中添加 console.log('User connected');
,但这从来没有显示。
我如何能够在一个文件中使用 Socket.IO,在另一个文件中使用文件服务器,并且仍然期望两者都能正确操作?