I am very new to Node.js and have been following a game-making tutorial, found here: http://rawkes.com/articles/creating-a-real-time-multiplayer-game-with-websockets-and-node.html
I am trying to improve on the game detailed in the tutorial by sending all the necessary files to the client.
When I connect to my server as a client, this error is thrown in the server terminal,
_http_outgoing.js:344
throw new Error('Can\'t set headers after they are sent.');
^
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
at Array.write (/Users/Mark/node_modules/express/node_modules/finalhandler/index.js:164:9)
at listener (/Users/Mark/node_modules/express/node_modules/on-finished/index.js:169:15)
at onFinish (/Users/Mark/node_modules/express/node_modules/on-finished/index.js:100:5)
at callback (/Users/Mark/node_modules/express/node_modules/on-finished/node_modules/ee-first/index.js:55:10)
at IncomingMessage.onevent (/Users/Mark/node_modules/express/node_modules/on-finished/node_modules/ee-first/index.js:93:5)
at emitNone (events.js:67:13)
at IncomingMessage.emit (events.js:166:7)
at endReadableNT (_stream_readable.js:921:12)
at nextTickCallbackWith2Args (node.js:442:9)
Here is the offending code:
var util = require("util"),
Player = require("./Player").Player;
var app = require('express')();
var http = require('http');
var httpServer = http.createServer(app);
httpServer.listen(8000)
var io = require('socket.io');
var socket,
players;
app.get('/', function(req, res){
res.sendFile(__dirname + '/public/index.html');
res.sendFile(__dirname + '/public/js/game.js');
res.sendFile(__dirname + '/public/js/Keys.js');
res.sendFile(__dirname + '/public/js/Player.js');
res.sendFile(__dirname + '/public/js/requestAnimationFrame.js');
res.sendFile(__dirname + '/public/style/game.css');
res.sendFile(__dirname + '/public/style/reset.css');
});
function init() {
players = [];
socket = io.listen(httpServer)
//streamline
socket.configure(function() {
socket.set("transports", ["websocket"]);
socket.set("log level", 2);
});
setEventHandlers()
}
init()
Any suggestions on getting this code working would be highly appreciated. I'm sure the solution is obvious but nothing I could find seemed to work.
setHeaderover response object ?res.sendFile()multiple times. The client will request the other files and you create routes for them in your express app so when the client requests them, you will send the appropriate file matching the desired request. You can useexpress.static()to set up route handling for all your static files with one line of code.