Question

Im fairly new to NodeJS(using c9.io) and have this sick obsession with it lately.

I would like to know while using NodeJS. Is it possible to stream the contents of a basic html page, not large, and not special to lets say 10 concurrent users. However if there is a change to that html page the users will instantly see the changes. This can be based on whatever event but basically on the file contents being updated. Im really hoping to create some simple prototype to impress the boss and do it with NodeJS with hopes to get ride of our current out-dated use of setInterval ajax posts. puke

  1. What is the name of this process because i keep hearing different names.
  2. Is it Possible?
  3. What else would i need in addition to NodeJS
  4. Where is a good starting point?

Thanks

Was it helpful?

Solution

Ok, here is a really simple example. A textarea synchronizes with login members.

Please install http, socket.io and express(ver3).

sudo npm install http, socket.io, express

And create a javascript file.

server.js

var app = require('express')(), 
  server = require('http').createServer(app), 
  io = require('socket.io').listen(server),
  member_sockets = {},
  key;

server.listen(80);

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});

io.sockets.on('connection', function (socket) {
  var user_id = socket.id;

  member_sockets[user_id] = socket;
  console.log("[login]-->", user_id);

  socket.on('txt_change', function (data) {
    for (key in member_sockets) {
      if (key != user_id) {
        member_sockets[key].emit("txt_change", data);
      }
    };
  });


  socket.on('disconnect', function (socket) {
    console.log("[logout]-->", user_id);
    delete member_sockets[user_id];
  });
});

In the same directory, you also create an index.html file.

index.html

<!DOCTYPE html>
<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
    <script src="/socket.io/socket.io.js"></script>
    <script>
      var socket = io.connect('http://localhost');
      socket.on('txt_change', function (data) {
        console.log(data);
        $("#txt").val(data.txt);
      });
      $(document).ready(function(){
        $("#txt").keyup(function(){
          socket.emit('txt_change', { "txt" : $(this).val() });
        });
      });
    </script>
  </head>
  <body>
    <textarea id="txt" style="width:200px;height:100px"></textarea>
  </body>
</html>

Then run the server with this command:

sudo node server.js

So the code should work like this picture: enter image description here

OTHER TIPS

Did you check socket.io? You can create the push server easily using socket.io module.

http://socket.io/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top