<!DOCTYPE html>
<html>
<head>
<title>Socket.io with JWTs</title>
</head>
<body>
<form id="login">
<input type="text" id="username" value="john" />
<input type="password" id="password" value="aaa" />
<input type="submit" value="login">
</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(token ? ('?token=' + token) : '', {
'forceNew': true
});
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>