const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
app.use(express.static(__dirname + '/'));
app.get('/', function (req, res) {
res.render('index');
});
// user connects
io.on('connection', function(socket){
// function sendMessage is called by frontend
socket.on('sendMessage', function(message){
// message is pushed to all connected sockets
io.emit('getMessage', message);
}
});
});
//_____Start server_____/
http.listen(8080, function () {
console.log('listening on *:8080');
});
// <script src="/socket.io/socket.io.js"></script>
// needs to be included in .html
var socket = io();
document.body.addEventListener('click', function() {
// Hallo Welt is pushed to backend on body click
socket.emit('sendMessage', "Hallo Welt");
}, true);
// Message is received from backend
socket.on('getMessage', function(msg){
console.log(msg);
});