-
-
Save JRSalasM/7c9ac7665a78056bda77d92facaca66a to your computer and use it in GitHub Desktop.
node.js express integrated with socket io, also with mysql and basic auth.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
all the important bits are here. | |
to use this you should create an express app using "express" code generation then use these files as an example. | |
license bsd/public domain |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Module dependencies. | |
*/ | |
var io = require('socket.io') | |
, sio, sio_client_on | |
, express = require('express') | |
, MemoryStore = express.session.MemoryStore | |
, routes = require('./routes') | |
, sessionStore = new MemoryStore(); | |
var app = module.exports = express.createServer(); | |
// Configuration | |
app.configure(function(){ | |
app.set('views', __dirname + '/views'); | |
app.set('view engine', 'ejs'); | |
app.use(express.cookieParser()); | |
app.use(express.session({store: sessionStore , secret: 'secret' , key: 'express.sid'})); | |
app.use(express.bodyParser()); | |
app.use(express.methodOverride()); | |
app.use(app.router); | |
app.use(express.static(__dirname + '/public')); | |
}); | |
app.configure('development', function(){ | |
app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); | |
}); | |
app.configure('production', function(){ | |
app.use(express.errorHandler()); | |
}); | |
// User validation | |
var auth = express.basicAuth(function(user, pass) { | |
return (user=="mypass"&&pass=="mypass") ? true : false; | |
},'Secret Area'); | |
// Routes | |
app.get('/', routes.index); | |
app.get('/testpage',auth, routes.t); | |
/// general program | |
var mysql = require('mysql'); | |
sqldb = mysql.createClient({user: 'root', database:'data'});/// no var, to the global scope; | |
var sql=sqldb; | |
sqldb.query("set names utf8"); | |
var dataslist; | |
// excaption handling | |
process.on('uncaughtException', function (err) { | |
console.log('Caught exception: ' + err.stack); | |
}); | |
// socket io set up | |
app.listen(3002); console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env); | |
sio = io.listen(app); | |
sio.set('log level', 1); | |
sio.secret_keyword='server' | |
var parseCookie = require('connect').utils.parseCookie; | |
sio.set('authorization', function (handshake_data, accept) { | |
var data = handshake_data; | |
if (data.headers.cookie) { | |
data.cookie = parseCookie(data.headers.cookie); | |
data.sessionID = data.cookie['express.sid']; | |
// (literally) get the session data from the session store | |
sessionStore.load(data.sessionID, function (err, session) { | |
if (err) { | |
// if we cannot grab a session, turn down the connection | |
accept(err.message, false); | |
} else { | |
data.session = session; | |
//console.log('data.session',data.session) | |
accept(null, true); | |
} | |
}); | |
} else { | |
// Check to see if the conection is made from the server | |
// ~ auth with token | |
if (data.query.secret_keyword && | |
(data.query.secret_keyword === sio.secret_keyword)) | |
{ | |
return accept(null, true); | |
} | |
return accept('No cookie transmitted.', false); | |
} | |
}); | |
sio.sockets.on('connection', function (socket) { | |
var hs = socket.handshake; | |
//console.log('connection',socket.handshake); | |
console.log('A socket with sessionID ' + hs.sessionID + ' connected!'); | |
// setup an inteval that will keep our session fresh | |
var intervalID = setInterval(function () { | |
// reload the session (just in case something changed, | |
// we don't want to override anything, but the age) | |
// reloading will also ensure we keep an up2date copy | |
// of the session with our connection. | |
if(hs&&hs.session)hs.session.reload( function () { | |
// "touch" it (resetting maxAge and lastAccess) | |
// and save it back again. | |
hs.session.touch().save(); | |
}); | |
}, 60 * 1000); | |
socket.on('disconnect', function () { | |
console.log('A socket with sessionID ' + hs.sessionID + ' disconnected!'); | |
// clear the socket interval to stop refreshing the session | |
clearInterval(intervalID); | |
}); | |
socket.join(socket.handshake.sessionID); | |
setup_socket_io(socket); | |
}); | |
function setup_socket_io(client) | |
{ | |
Object.keys(sio_client_on) | |
.forEach(function(eventName){ | |
var f=sio_client_on[eventName]; | |
client.on(eventName,function(){f.apply(client,arguments)});}); | |
} | |
//// socket io events | |
sio_client_on= | |
{ | |
'message': function (message) { | |
console.log("message",message) | |
//if (message.event == 'homepage loaded') { | |
//client.broadcast(...); | |
//} | |
}, | |
'test': function (d) { | |
console.log("test",d) | |
//if (message.event == 'homepage loaded') { | |
// this.broadcast('gotticks'); | |
//} | |
// sio.sockets.emit('eval','alert("Man, good to see you back!1")'); | |
//sio.sockets.in(req.sessionID).send('Man, good to see you back!'); | |
}, | |
'dataslist': function (d) { | |
this.emit('dataslist',dataslist); | |
console.log("dataslist",dataslist.length,d?d:'') | |
//if (message.event == 'homepage loaded') { | |
// this.broadcast('gotticks'); | |
//} | |
// sio.sockets.emit('eval','alert("Man, good to see you back!1")'); | |
//sio.sockets.in(req.sessionID).send('Man, good to see you back!'); | |
} | |
'update_something':function(d) | |
{ | |
sqldb.query("UPDATE datas SET something="+parseFloat(d.something)+" where dataid="+sql.escape(d.dataid)+"") | |
.on('error', function(err) {if (err) throw err;}) | |
.addListener('end', function() { setTimeout( selectdataslist,500); }) | |
} | |
} | |
app.get('/refresh', function (req, res) { // if this url called by some other server, all socket io clients of this app start to refresh data, i use it to update my window when the database is updated | |
res.end('ok'); | |
sio.sockets.emit('eval','if(refreshdata)refreshdata()'); // emit to all clients | |
}); | |
app.get('/getdata/:fromdate/:todate/:id?', function (req, res) { // example how to use params | |
res.send([req.params.fromdate,req.params.todate,req.params.id]); // retun json with the arguments | |
}); | |
app.get('/dataslist', function (req, res) { | |
res.send(datalist); // send json data | |
}); | |
function selectdatalist(cb) | |
{ | |
console.log('select dataslist called'); | |
var tdataslist=[]; | |
sqldb.query("SELECT * FROM datas where updated=1") | |
.on('error', function(err) {if (err) throw err;}) | |
.addListener('row', function(r) { tdataslist.push(r);}) | |
.addListener('end', function() { dataslist=tdataslist;if(cb)cb(); }) | |
} | |
setInterval(selectdataslist,120*1000); | |
setTimeout( selectdataslist,500); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<input type="button" onclick="getdata()" value="load data"> | |
<input type="button" onclick="reload_datadata()" value="load same data again"> | |
<span style="margin-right:30px;" id="data_status"></span> | |
<script> | |
var status_timeout | |
function setStatus(message,color,keep) | |
{ | |
if(status_timeout)clearTimeout(status_timeout); | |
$('#data_status').html(message).css({color:color}); | |
if(!keep) | |
status_timeout=setTimeout(function(){ | |
$('#data_status').html("") | |
},2000); | |
} | |
function selectdata(id,title) | |
{ | |
window.document.title=title; | |
$('#dataid').val(id); | |
$('#dataname').html(title); | |
$('#dataname2').val(title); | |
get_something(); | |
setTimeout(getdata(),500); | |
} | |
var datadata,datadata2,datadata3,chart,chart_min=null; | |
function update_something() | |
{ | |
if($('#dataid').val()=="") { console.log ('dataid=empty'); setStatus('dataid=empty','red',true); return; } | |
socket.emit('update_something',{dataid:$('#dataid').val(),something:$('#something').val()}); | |
} | |
function get_something() | |
{ | |
if($('#dataid').val()=="") { console.log ('dataid=empty'); setStatus('dataid=empty','red',true); return; } | |
} | |
function refreshdata()// this function is called by eval comand from the server | |
{ | |
console.log('refresh'); | |
setStatus('refresh','green',false); | |
//alert('refersh') | |
getdata(); | |
} | |
function getdata() | |
{ | |
if($('#dataid').val()=="") { console.log ('dataid=empty'); setStatus('dataid=empty','red',true); return; } | |
console.log('getdata'); | |
setStatus('getdata','green',true); | |
socket.emit('datadata',{ | |
fromdate:$("#fromdate").datepicker( "getDate"),todate: $("#todate").datepicker( "getDate"), | |
dataid: $("#dataid").val(), | |
usepercent: $("#usepercent_enabled")[0].checked | |
}); | |
} | |
re_jsondate = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)(Z|([+\-])(\d{2}):(\d{2}))$/ | |
function dateReviver (key, value) { | |
if (typeof value === 'string') { | |
var a=re_jsondate.exec(value); | |
if (a) { | |
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); | |
} | |
} | |
return value; | |
} | |
function JSONparse (data) { | |
try { return JSON.parse(data,dateReviver) } | |
catch (e) { return false } | |
} | |
//// datas list | |
var dataslist=[]; | |
////// example bind a function to an event: | |
socket.on('dataslist',function(d) | |
{ | |
console.log ('got datalist'); setStatus('got datalist','green',false); | |
fill_dataslist(d); | |
console.log ('datalist updated'); setStatus('datalist updated','green',false); | |
}); | |
////// call some event in the saerver | |
socket.emit('dataslist'); // do some action during page load | |
console.log ('asking datalist'); setStatus('asking datalist','green',false); | |
////chart | |
var lastdata_receive_datadata; | |
function reload_datadata(){ receive_datadata(lastdata_receive_datadata); } | |
function receive_datadata(d) | |
{ | |
console.log('receive_datadata'); | |
setStatus('receive_datadata','green',false); | |
if(!d||d.length==0) { console.log("no data"); setStatus('no data','red',true); return;} | |
lastdata_receive_datadata=d; | |
drawchart(); | |
} | |
////// example bind a function to an event: | |
socket.on('datadata',receive_datadata); | |
</script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ie console antibug: | |
var consolelog=[]; | |
var consolelogdiv; | |
if(!console)console={}; | |
log2=function(){var s=""; for(var x=0;x<arguments.length;x++)s+=(x>0?' ':'')+arguments[x];consolelog.push(s);if(consolelogdiv) consolelogdiv[0].innerText=consolelog.join("\r\n\r\n");}; | |
if(!console.log) console.log=log2; | |
function showlog() | |
{ | |
consolelogdiv=$("<div/>",{id:'consolelog'}); | |
//var consolelogdivw=$("</div>",{id:'consolelogw'}); | |
// consolelogdiv.css({position:'relative',height:'100%',width:'100%'}).draggable().resizable().appendTo(document.body); | |
consolelogdiv.css({position:'absolute',top:'20px','z-index':'1000000',left:'20px',height:'30%',width:'30%','background-color':'rgba(255,255,255,0.75)',border:"1px solid lightgray"}).appendTo(document.body); | |
consolelogdiv.width(consolelogdiv.width()) | |
consolelogdiv.height(consolelogdiv.height()) | |
consolelogdiv.dblclick(consolelogdiv.height()) | |
$("#consolelog").resizable() | |
consolelogdiv[0].innerText=consolelog.join("\r\n"); | |
}; | |
var socket =io.connect(undefined,{ 'connect timeout': 1000 , 'try multiple transports': false }); | |
/* | |
socket.on('connect', function () { | |
window.status='connected'; | |
}); | |
socket.on('disconnect', function () { | |
window.status='disconnected'; | |
}); | |
*/ | |
// just one event on client: | |
socket.on('eval', function (d) { | |
eval(d); | |
}); | |
socket.on('message', function (d) { | |
alert(d); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title><%= title %></title> | |
<!-- my files --> | |
<link rel='stylesheet' href='/stylesheets/style.css' /> | |
<script type="text/javascript" src="/socket.io/socket.io.js"></script> | |
<script type="text/javascript" src="/javascripts/general.js"></script> | |
</head> | |
<body> | |
<%- body %> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment