Archive for the ‘Node.js’ category

Using Socket.IO with Backbone.js

March 6th, 2013

I work on a lot of different projects, some for work and some for fun and some on the side.  I have been working on a social application here lately that will have lots of topics and within those topics they will have comments.  I felt like the ‘Room’ concept of socket.io would be a good fit for this idea so I began implementing it for this project.  When I first set up socket I was having a problem because stupid me had some javascript that was formatted incorrectly and the engine was not throwing an error with it because it translated to good javascript.  In the meantime while I was doing all of that I had stuck the socket connection in a global variable so it was only making one connection, that does seem to be how you would want your socket.io application to be setup anyways.

I have included the final code below of the solution that is working for me with my backbone views, it turns out I had to create a new socket.io connection each time a topic was clicked on by the user, due to the fact that I am ‘joining’ them to that room, identified by the TopicID.  When I had the socket defined globally, I was getting duplicate messages back to my clients and my only reasoning was that I had the single connection so my clients were getting those dupes back at them.

If you have anything you could throw in for me with input, I would really appreciate it as I think this setup is not a very scalable one, thanks.

//server.js
var io = require('socket.io').listen(server);
io.sockets.on('connection', function(socket) {
  console.log('Socket Connection Made - Server Side');
  socket.on("leaveRoom", function(data){
      console.log('Leaving room ' + data.room);
      socket.leave(data.room);
  });
  socket.on("setRoom", function(data){
      console.log('Joining room ' + data.room);
      socket.join(data.room);
  });

  socket.on('comment', function(data) {
    console.log('Emitting comment');
    socket.broadcast.to(data.room).emit('comment', data.comment);
  });
});

//client.js
//in backbone view initialize()
var url = "http://localhost:3000";
this.socket = io.connect(url);
this.socket.on('connect', function () {
    that.socket.emit("setRoom", {room: that.model.get("TopicId")});
});
this.socket.on('comment', function (data) {
     $('#commentsList').prepend(data);
});

//here is the code to tell server a new comment has been published
that.socket.emit('comment',{ comment: msg, room: that.model.get("TopicId")} );

My first little Node.js App

January 24th, 2013

If you are a developer and you haven’t heard about node.js, what rock have you been living under??  Anyways, if you have been hearing about it and would like to learn more, head over to their site HERE and download it and start playing with it.  Its super easy to get going with node, once you install it, all you have to do is open a terminal window and type node “name_of_file.js”, with the correct javascript in it, of course.

I just wrote up this quick little example to see if I could get node to act like a webserver, so here is the js code for it below:

var http = require('http');
var fs = require('fs');
http.createServer(function (req, response) {
    fs.readFile('index.html', function (error, content) {
        if (error) {
            response.writeHead(500);
            response.end();
        }
        else {
            response.writeHead(200, { 'Content-Type': 'text/html' });
            response.end(content, 'utf-8');
        }
    });

}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

Just create a directory anywhere on your system and create a file with index.html (That’s my example, it can be anything) and then simply issue this command in the terminal window.

node “name_of_file.js”

My example is this: node server.js.

You will get a ‘Server running at http://127.0.0.1:1337/’ message after that and that will let you know that node is running correctly, all you have to do after that is open a web browser and go to the address of http://127.0.0.1:1337 and you should have the webpage you built, you may want to just slap some text in there so you see something.

I hope this helps someone, I plan on delving into the node realm a lot more in the coming weeks, so look for other posts down the road.