Running the server
Before we start using Socket.IO, let's first write a simple Node.js server code, which responds with the chat's page. We can see the server code as follows:
var http = require('http'), fs = require('fs'), port = 3000, html = fs.readFileSync(__dirname + '/html/page.html', {encoding: 'utf8'}), css = fs.readFileSync(__dirname + '/css/styles.css', {encoding: 'utf8'}); var app = http.createServer(function (req, res) { if(req.url === '/styles.css') { res.writeHead(200, {'Content-Type': 'text/css'}); res.end(css); } else { res.writeHead(200, {'Content-Type': 'text/html'}); res.end(html); } }).listen(port, '127.0.0.1');
The preceding code should be placed in /index.js
. The script starts with the definition of several global variables. The http
module is used to create the server, and the fs
module is used to read the CSS...