Socket.io - Introduction SOCKET.IO
Socket.io - Introduction
The web framework
The first goal is to setup a simple HTML webpage that serves out a form and a list of messages. We’re going to use the Node.JS web framework express
to this end. Make sure Node.JS is installed.
First, let’s create a package.json
manifest file that describes our project. I recommend you place it in a dedicated empty directory (I’ll call mine chat-example
).
{ "name": "socket-chat-example", "version": "0.0.1", "description": "my first socket.io app", "dependencies": {} } |
Now, in order to easily populate the dependencies
property with the things we need, we’ll use npm install
:
npm install express@4.15.2 |
Now that express is installed we can create an index.js
file that will setup our application.
var app = require('express')(); var http = require('http').createServer(app); app.get('/', function(req, res){ res.send('<h1>Hello world</h1>'); }); http.listen(3000, function(){ console.log('listening on *:3000'); }); |
This translates into the following:
- Express initializes
app
to be a function handler that you can supply to an HTTP server (as seen on line 2). - We define a route handler
/
that gets called when we hit our website home. - We make the http server listen on port 3000.
If you run node index.js
you should see the following:
And if you point your browser to https://localhost:3000
: