Wednesday, July 04, 2012

Exploring ExpressJS & Socket.IO

The next line of action today was to check the working of Socket.IO along with Express. Took me a while to get my sample working, here it goes if someone likes to use.

Index.html to be present in the same directory.

<html>
<head>
<title>Test - Node Views</title>
<script src="/socket.io/socket.io.js"></script>
 
<script>
var socket = io.connect('http://localhost:8080');
 
socket.on('connect',function() {
  console.log('Client has connected to the server!');
});
 
socket.on('news', function (data) {
  console.log(data);
  socket.emit('newsresponse', 'this is new response');
});
</script>
 
</head>
 
<body bgcolor="#ffffff" text="#000000"></body>
 
</html>

Server.js

var express = require('express');
var io = require('socket.io');
var http = require('http');
 
var app = express();
var server = http.createServer(app);
var listener = io.listen(server);
 
app.configure(function(){
  app.use(app.router);
  app.use(express.static(__dirname + '/'));
});
 
listener.on('connection', function (socket) {
 
  console.log('Connection to client established');
 
  socket.emit('news', 'this is the news');
 
  socket.on('newsresponse', function (data) {
    console.log(data);
  });
 
  socket.on('disconnect',function(){
    console.log('Server has disconnected');
  });
 
});
 
server.listen(8080);
 

3 comments:

  1. That was an interesting material. You should enlarge this topic, as I think. I would like to see here more related posts.

    ReplyDelete
  2. I really like your blog. You share with us a very valuable and useful information to work on the computer.

    ReplyDelete
  3. Well, I'll try to make it this way. Thank you for posting those materials here. I do appreciate your work a lot.

    ReplyDelete