Game Development Reference
In-Depth Information
We list the mime types as follows:
var mimeTypes = {
"html": "text/html",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"png": "image/png",
"js": "text/javascript",
"json": "text/javascript",
"css": "text/css"};
The HTTP request handler reads the request URL (for example,
http://127.0.0.1/10-Multiple-Player-Programming-Spectator.html )
and retrieves the path name (for example, 10-Multiple-Player-Programming-
Spectator.html ). To retrieve the physical path, it appends the path to the physical
path ( process.cwd() ) concatenated with the /client folder. We concatenate the
/client folder name as we want to render only files of that folder. We use path
modules function, join , to generate the physical path and use the reader stream
pipe function to render the file. We also set the content type based on the file
extension and retrieve the corresponding mime type from the mimeTypes array.
The following code is of the handler function:
function handler(req, res) {
var uri = url.parse(req.url).pathname;
var filename = path.join(process.cwd(),'/client', uri);
path.exists(filename, function(exists) {
if(!exists) {
console.log("not exists: " + filename);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('404 Not Found\n');
res.end();
return;
}
var mimeType = mimeTypes
[path.extname(filename).split(".")[1]];
res.writeHead(200, {'Content-Type':mimeType});
var fileStream = fs.createReadStream(filename);
fileStream.pipe(res);
}); //end path.exists
}
http.listen(80);
The socket server waits for the client request:
io.sockets.on('connection', function (socket) {
 
Search WWH ::




Custom Search