Skip to content

Instantly share code, notes, and snippets.

@joates
Last active December 21, 2015 13:29
Show Gist options
  • Save joates/6313364 to your computer and use it in GitHub Desktop.
Save joates/6313364 to your computer and use it in GitHub Desktop.
express http server (includes some boilerplate socket.io but thats just "gravy" :) 1) install node (http://nodejs.org/download) 2) download the 3 files from this Gist 3) run `npm install` 4) run `node server.js` 5) visit "http://localhost:8000" in your browser 6) browse anywhere within <webroot> OR click on "index.html" for the websockets demo
<!DOCTYPE html>
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<h2>Open the debug console</h2><p>(<em>F12 / Ctrl+Shift+K</em>) to view websocket messages</p>
</body>
<script>
window.onload = function() {
//
var socket = io.connect('http://localhost:8000')
, seq = 0
socket.on('message', function (msg) {
console.log( JSON.stringify(msg) )
})
window.setInterval(function() {
socket.emit('message', { seq: ++seq, data: 'websocket message!' })
}, 1000)
}
</script>
</html>
{
"name": "server",
"description": "generic express http server.",
"author": "joates",
"license": "MIT",
"version": "0.0.1",
"main": "server.js",
"dependencies": {
"express": "3.3.x",
"socket.io": "0.9.x"
},
"engine": {
"node": "0.10.x"
}
}
// server.js
// by joates (Aug-2013)
var express = require('express')
, http = require('http')
, io = require('socket.io')
, app = express()
var port = process.env.PORT || 8000
, webroot = __dirname + '/'
app.use(express.favicon())
app.use(express.directory(webroot));
app.use(express.static(webroot))
app.log = function() {
var d = new Date()
, dTime = d.toTimeString().substr(0, 8)
, aArgs = [ dTime + ' ' + arguments[0] ]
console.log.apply(this, aArgs)
}
var server = http.createServer(app).listen(port, function() {
console.log(' Express server listening on port ' + port)
})
//
// Socket.IO server set up & configuration.
var sio = io.listen(server)
sio.configure(function () {
sio.set('log level', 0)
sio.set('authorization', function (handshakeData, callback) {
callback(null, true) // error first callback style
})
})
// Register event handlers & callbacks.
sio.sockets.on('connection', function (socket) {
socket.on('message', function(msg) {
//
app.log( JSON.stringify(msg) )
socket.send('got seq #' + msg.seq + '.. thanks!')
})
socket.on('disconnect', function() {
//
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment