Skip to content

Instantly share code, notes, and snippets.

@shime
Created October 5, 2013 05:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shime/6837023 to your computer and use it in GitHub Desktop.
Save shime/6837023 to your computer and use it in GitHub Desktop.
var express = require('express')
, app = express()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server);
server.listen(4000);
app.get('/', function(request, response){
response.sendfile(__dirname + "/index.html");
});
var activeClients = 0;
io.sockets.on('connection', function(socket){clientConnect(socket)});
function clientConnect(socket){
activeClients +=1;
io.sockets.emit('message', {clients:activeClients});
socket.on('disconnect', function(){clientDisconnect()});
}
function clientDisconnect(){
activeClients -=1;
io.sockets.emit('message', {clients:activeClients});
}
<!DOCTYPE html>
<html>
<head>
<title>Connection Counter</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
function msgReceived(msg){
$clientCounter.html(msg.clients);
}
$(document).ready(function () {
$clientCounter = $("#client_count")
var socket = io.connect('http://localhost:4000');
socket.on('message', function(msg){msgReceived(msg)});
});
</script>
</head>
<body>
<p><span id="client_count">0</span> connected clients</p>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment