Skip to content

Instantly share code, notes, and snippets.

@viktorstrate
Created December 14, 2016 17:31
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 viktorstrate/61f061e6fc0045912d76da2ed321bead to your computer and use it in GitHub Desktop.
Save viktorstrate/61f061e6fc0045912d76da2ed321bead to your computer and use it in GitHub Desktop.
An example of socket.io
/***
/* Example by Viktor Hundahl Strate
*/
// The server stored in the variable 'app', with the function on line 12 called 'handler'
var app = require("http").createServer(handler),
// Imports the socket.io in the folder 'node_modules'
io = require("socket.io").listen(app),
// Imports the file server
fs = require("fs");
// Starts the server on port '8000'
app.listen(8000);
// Handler is called when somone joins the server, and it shows the 'index.html' file, to the user.
function handler(req, res){
// Reads the file 'index.html'
fs.readFile("index.html", function (err, data){
// Sets the response code to 200 aka OK
res.writeHead(200);
// Sends the data from the 'index.html' file to the user.
res.end(data);
})
}
// When somone connects to the server it gets called
io.sockets.on('connection', function(socket){
// Sends out some data with the name 'news'
socket.emit('news', {hello: "world"});
// Waits to somone sends out some data with the name 'back',
// and when it happends get the data
socket.on('back', function(data){
// logs out the data in the console
console.log(data);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment