1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| // import lib
var express = require('express');
var http = require('http');
var io = require('socket.io');
// init express
var app = express();
app.configure(function() {
app.use(express.static(__dirname + '/public'));
});
app.get('/', function(req, res, next) {
res.render('./public/index.html');
});
// init http server
var server = http.createServer(app);
server.listen(8333);
// init socket
var socket = io.listen(server);
var allClients = 0;
var clientId = 1;
socket.on('connection', function(client) {
var my_timer;
var my_client = {
"id" : clientId,
"obj" : client
};
clientId += 1;
allClients += 1;
my_timer = setInterval(function() {
my_client.obj.send(JSON.stringify({
"timestamp" : (new Date()).getTime(),
"clients" : allClients
}));
}, 1000);
client.on('message', function(data) {
my_client.obj.broadcast.send(JSON.stringify({
"message" : "poke send by client " + my_client.id
}));
console.log(data);
});
client.on('disconnect', function() {
clearTimeout(my_timer);
allClients -= 1;
console.log('disconnect');
});
}); |
Partager