Skip to content

Instantly share code, notes, and snippets.

@unoseistres
Created November 9, 2014 18:52
Show Gist options
  • Save unoseistres/f129792d43095e287759 to your computer and use it in GitHub Desktop.
Save unoseistres/f129792d43095e287759 to your computer and use it in GitHub Desktop.
//////////////////////////////// HTTP Portion
var http = require('http');
var fs = require('fs'); // Using the filesystem module
var path = require('path');
var httpServer = http.createServer(requestHandler);
httpServer.listen(8088);
/*
function requestHandler(req, res) {
// Read index.html
fs.readFile(__dirname + '/index.html',
// Callback function for reading
function (err, data) {
// if there is an error
if (err) {
res.writeHead(500);
return res.end('Error loading canvas_socket.html');
}
// Otherwise, send the data, the contents of the file
res.writeHead(200);
res.end(data);
}
);
}
*/
function requestHandler(req, res) {
///PATHNAME STUFF
var pathname = req.url;
if (pathname == '/') { // if blank let's ask for index.html
pathname = '/mobile.html';
}
var ext = path.extname(pathname); // what's our file extension
var typeExt = { // map extension to file type
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css'
};
var contentType = typeExt[ext] || 'text/plain';
// Now read and write back the file with the appropriate content type
fs.readFile(__dirname + pathname,
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading ' + pathname);
}
res.writeHead(200,{ 'Content-Type': contentType }); // dynamically setting content type
res.end(data);
}
);
}
// WebSocket Portion
// WebSockets work with the HTTP server
var io = require('socket.io').listen(httpServer);
// Register a callback function to run when we have an individual connection
// This is run for each individual user that connects
io.on('connection',
// We are given a websocket object in our function
function (socket) {
console.log("We have a new client: " + socket.id);
// When this user emits, client side: socket.emit('otherevent',some data);
socket.on('chatmessage', function(data) {
// Data comes in as whatever was sent, including objects
console.log("Received: 'chatmessage' " + data);
// Send it to all of the clients
io.emit('chatmessage', data);
});
socket.on('backcolor', function(data) {
// Data comes in as whatever was sent, including objects
console.log("Received: 'backcolor' " + data);
// Send it to all of the clients
/* io.emit('backcolor', data); */
socket.broadcast.emit('backcolor', data);
});
socket.on('disconnect', function() {
console.log("Client has disconnected " + socket.id);
});
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment