add example

This commit is contained in:
José F. Romaniello 2014-01-14 11:04:41 -03:00
parent 86f4fd43ab
commit e62618837c
2 changed files with 117 additions and 0 deletions

65
example/public/index.html Normal file
View File

@ -0,0 +1,65 @@
<!DOCTYPE html>
<html>
<head>
<title>Socket.io with JWTs</title>
</head>
<body>
<form id="login">
<input type="text" id="username" />
<input type="password" id="password" />
<input type="submit">
</form>
<div>
<button id="ping">Send Socket.io Ping</button>
</div>
<script src="//code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var token, socket;
function connect () {
socket = io.connect('', {
'force new connection': true,
query: token ? 'token=' + token : undefined
});
socket.on('pong', function () {
console.log('- pong');
}).on('time', function (data) {
console.log('- broadcast: ' + data);
}).on('authenticated', function () {
console.log('- authenticated');
}).on('disconnect', function () {
console.log('- disconnected');
});
}
connect(); //connect now, it will drop
$('#ping').on('click', function () {
console.log('- ping');
socket.emit('ping');
});
$('#login').submit(function (e) {
e.preventDefault();
var username = $('username').val();
var password = $('password').val();
$.ajax({
type: 'POST',
data: {
username: username,
password: password
},
url: '/login'
}).done(function (result) {
token = result.token;
connect();
});
});
</script>
</body>
</html>

52
example/server.js Normal file
View File

@ -0,0 +1,52 @@
var express = require('express');
var http = require('http');
var socketIo = require('socket.io');
var socketio_jwt = require('../'); //require('socketio-jwt');
var jwt = require('jsonwebtoken');
var jwt_secret = 'foo bar big secret';
var app = express();
app.configure(function(){
this.use(express.json());
this.use(express.static(__dirname + '/public'));
});
app.post('/login', function (req, res) {
var profile = {
first_name: 'John',
last_name: 'Doe',
email: 'john@doe.com',
id: 123
};
// We are sending the profile inside the token
var token = jwt.sign(profile, jwt_secret, { expiresInMinutes: 60*5 });
res.json({token: token});
});
var server = http.createServer(app);
var sio = socketIo.listen(server);
sio.set('authorization', socketio_jwt.authorize({
secret: jwt_secret,
handshake: true
}));
sio.sockets
.on('connection', function (socket) {
socket.on('ping', function (m) {
socket.emit('pong', m);
});
});
setInterval(function () {
sio.sockets.emit('time', Date());
}, 5000);
server.listen(9000, function () {
console.log('listening on http://localhost:9000');
});