Sol websockets reloj

De wikiserver
Dreceres ràpides: navegació, cerca

CLIENTE

<!DOCTYPE html>
<html>
  <head>
<script src="./node_modules/socket.io-client/dist/socket.io.js"></script>
<script>

//tenemos en http://localhost:8080 y escuchamos el evento messages.
var socket = io.connect('http://localhost:8080', { 'forceNew': true });




socket.on('time', function(data) {
                addMessage(data.time);
            });


function addMessage(message) {
                var text = document.createTextNode(message),
                    el = document.createElement('li'),
                    messages = document.getElementById('messages');

                el.appendChild(text);
                messages.appendChild(el);
            }

            


</script>
      
  </head>
  <body>
    <h1>MI RELOJ</h1>
    <div id="messages"></div>

  <body/>
</html>

SERVIDOR

var express = require('express');
var path = require('path');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io').listen(server);



//Pondremos el servidor a escuchar en localhost con el puerto 8080
server.listen(8080, function() {
	console.log('Servidor corriendo en http://localhost:8080');
});


app.use(express.static(path.join(__dirname, '/')));



//  connection
// Send current time to all connected clients
function sendTime() {
    io.sockets.emit('time', { time: new Date().toJSON() });
}

// Send current time every 10 secs
setInterval(sendTime, 1000);



// otra forma

/*io.on('connection', function(socket) {
  console.log('Un cliente se ha conectado');
   //  connection
// Send current time to all connected clients
function sendTime() {
    io.sockets.emit('time', { time: new Date().toJSON() });
}

// Send current time every 10 secs
setInterval(sendTime, 1000);
});

*/