###Simple Socket.io Setup
We will use npm to manage the node modules we need for this project.
In you project folder, from the terminal enter
npm init
and follow the prompts. This will create a package.json file in your project's root directory.
Then from the terminal enter
npm install express http socket.io --save
This downloads all the node modules that we need. Now create the file server.js and index.html. From the terminal,
mkdir html
touch html/index.html
touch server.js
Your directory structure should now look like..
├── html
│ └── index.html
├── node_modules
│ └── (many node module files)
├── package.json
└── server.js
Now open up server.js and enter the following code.
server.js
var express = require('express'),
io = require('socket.io'),
http = require('http'),
app = express(),
server = http.createServer(app);
server.listen(3000);
var io = io.listen(server);
console.log('Up and running');
var startTime = Date.now();
var emitter;
//sockets
io.on('connection', function (socket) {
console.log('connection');
if(!emitter){
emitter= setInterval(function(){
io.emit('time',(Date.now()-startTime)/1000);
},100);
}
socket.on('resetTimer', function ( data) {
console.log(data);
startTime = Date.now();
});
});
//express routes
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.get('/socket',function(req,res){
res.sendFile(__dirname + '/html/index.html');
});
Here we setup our express server and the server side of socket.io. After the first user connects a socket, the app will infinitely emit events every 10th of a second displaying elapsed seconds since the first connection. Forever. The app will also listen for a reset event, which resets the start time.
html/index.html
<!DOCTYPE html>
<html>
<head>
<title>Simmple Socket HTML</title>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('time', function(data){
document.getElementById("count").innerHTML = data;
});
function emitResetTimer(){
console.log('resetting');
socket.emit('resetTimer', 'Reset timer');
}
</script>
</head>
<body>
<h3>Socket Test</h3>
Time: <div id="count"></div>
<input value="reset timer" type="button" onclick="emitResetTimer();" />
</body>
</html>
The client essentially mirrors the server. It listens for time events and emits resetTimer events.
To run, from the terminal enter
node server.js
And in your brower, go to
http://localhost:3000/socket