Game Development Reference
In-Depth Information
Implementing the HTTP server using Node.js
Node.js comes with a built-in HTTP module. The following sample code listing
explains how to work with a node HTTP server.
We are discussing the node HTTP server because once your
game page uses WebSockets, we cannot simply click on the
HTML page to run a WebSocket client. The WebSocket client
page should come from the same domain as the WebSocket
server, otherwise it may give security issues. Hence, we
need to request the HTML page from a web server running
WebSocket of the same port.
The first line will import an http module and can also be used to load the module
installed by NPM.
Open the server.js file in your editor. It contains the following line of code:
var http = require('http');
The http module with the createServer function creates a server object:
var httpserver = http.createServer();
Node.js is completely event-based and an event defines the flow of code. It is basically
asynchronous by design. When we start the server, it first creates the HTTP server
object and waits for incoming HTTP requests. When it receives a request, the on event
handler is invoked with the request ( req ) and response( res ) as the parameters:
httpserver.on('request', function(req, res) {
After receiving the request, the server sets the HTTP header status code to 200 and
sets the content type to plain text:
res.writeHead(200, {'Content-Type': 'text/plain'});
Then, it writes a string to the response objects:
res.write('Hello Game World!');
It then flushes the response buffer by invoking the end method:
res.end(); });
The server is set to start at port 4000 by the following line of code:
server.listen(4000);
 
Search WWH ::




Custom Search