Created
September 25, 2019 15:11
-
-
Save raclim/b0831c3f16ba12575a892abda9b5faef to your computer and use it in GitHub Desktop.
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
// HTTP Portion | |
var http = require('http'); | |
var fs = require('fs'); // Using the filesystem module | |
var httpServer = http.createServer(requestHandler); | |
var url = require('url'); | |
httpServer.listen(8080); | |
function requestHandler(req, res) { | |
var parsedUrl = url.parse(req.url); | |
console.log("The Request is: " + parsedUrl.pathname); | |
fs.readFile(__dirname + parsedUrl.pathname, | |
// Callback function for reading | |
function (err, data) { | |
// if there is an error | |
if (err) { | |
res.writeHead(500); | |
return res.end('Error loading ' + parsedUrl.pathname); | |
} | |
// Otherwise, send the data, the contents of the file | |
res.writeHead(200); | |
res.end(data); | |
} | |
); | |
} | |
// WebSocket Portion | |
// WebSockets work with the HTTP server | |
let 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.sockets.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('othermouse', function(data) { | |
// Data comes in as whatever was sent, including objects | |
console.log("Received: 'othermouse' " + data.x + " " + data.y); | |
// Send it to all of the clients | |
socket.broadcast.emit('othermouse', 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