Game Development Reference
In-Depth Information
Execute the following command to start the server:
node server.js
Let's walk through another sample code, which reads a file and sends its contents
as a response:
var fs = require('fs');
var http=require('http')
var server=http.createServer(handler);
server.listen(4000);
function handler(req, res) {
res.writeHead(200, {'Content-Type': 'video/mp4'});
var rs = fs.createReadStream('test.mp4');
rs.pipe(res);
}
The preceding code uses another powerful node module, fs , which stands for
filesystem. The fs module offers a wide variety of functions to read and write to
file using streams.
The preceding code requests the fs module object. It helps us create the file read
stream. Then, when the server receives a request, it sets a response header content
type to 'video/mp4' . Node.js offers a very powerful function, pipe . This function
avoids the slow client problem. If the client is slow, we do not want to fill up our
memory with unflushed buffers. So, we pause the read stream and when the
consumer has finished reading the data, we resume. We do not want to manage the
resuming and pausing of the buffers/streams. Hence, the pipe function manages it
for you. It is a function of readable stream interface and takes the destination writable
stream interfaces as an argument and manages the complete read/write cycle. In our
case, the read stream ( rs ) is our file and the write stream is our response ( res ) object
( rs.pipe(res); ).
Understanding Socket.IO
Socket.IO is available as a separate NPM module. It can be installed using the
following command:
npm install socket.io
Socket.IO implements a socket server and also provides a unified client library
that does not distinguish between clients, using WebSockets or any other type of
mechanism such as flash sockets. It provides a unified API that abstracts away the
implementation details of WebSockets.
 
Search WWH ::




Custom Search