Skip to content

Instantly share code, notes, and snippets.

@FazioNico
Created September 15, 2020 20:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FazioNico/17c4f2e99098624abccadbcbc39afce3 to your computer and use it in GitHub Desktop.
Save FazioNico/17c4f2e99098624abccadbcbc39afce3 to your computer and use it in GitHub Desktop.
// Based off of Shawn Van Every's Live Web
// http://itp.nyu.edu/~sve204/liveweb_fall2013/week3.html
// Using express: http://expressjs.com/
var express = require('express');
// Create the app
var app = express();
// Set up the server
// process.env.PORT is related to deploying on heroku
var server = app.listen(process.env.PORT || 3000, listen);
// This call back just tells us that the server has started
function listen() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://' + host + ':' + port);
}
app.use(express.static('public'));
// WebSocket Portion
// WebSockets work with the HTTP server
var io = require('socket.io')(server);
// 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('mouse',
function(data) {
// Data comes in as whatever was sent, including objects
console.log("Received: 'mouse' " + data.x + " " + data.y);
// Send it to all other clients
socket.broadcast.emit('mouse', data);
// This is a way to send to everyone including sender
// io.sockets.emit('message', "this goes to everyone");
}
);
socket.on('disconnect', function() {
console.log("Client has disconnected");
});
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment