node.js – Socket.IO

Dependencies
npm install socket.io

Server

var fs = require('fs');
var app = require('http').createServer(
  function(req, res) {
      // serwuj client.html
      fs.readFile('client.html', function(err, data) {
          res.writeHead(200);
          res.end(data);
      });
  }
);
app.listen(8081);
var io = require('socket.io').listen(app);
 
io.sockets.on('connection', function (socket) {
  // send welcome message
  socket.emit('from-server', { date: 'welcome to time service' });
 
  // send time on every second
  setInterval(function(){
    socket.emit('from-server', { date: new Date() });
  }, 1000);
 
  // log message from client
  socket.on('from-client', function (data) {
    console.log(data);
  });
});

Client

<div id="div"></div>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://localhost:8081/socket.io/socket.io.js"></script>
<script>
$(document).ready(function(){
  var socket = io.connect('http://localhost:8081');
  socket.on('from-server', function (data) {
    console.log(data);
    $('#div').html('<p>'+data.date+'</p>');
    socket.emit('from-client', { message: 'confirmation: i get date' });
  });
});
</script>

Go to: http://localhost:8081

Leave a Reply

Your email address will not be published. Required fields are marked *