Html5 Tutorial - Future Technology

Monday 2 December 2013

HTML5 Tutorial - Html5 tutorial two chat programs using node.js

In this tutorial we will learn how to use HTML5 WebSockets. We need a server that supports this protocol. We will use the NodeJS server, a very popular server for writing web applications that use WebSockets or for writing HTML5 games. It's a small, powerful server, that embeds the V8 JavaScript interpreter (the one in Chrome), enablind server side JavaScript. We will look at two versions of a small chat application, that use the socket.io and express modules for NodeJS. Socket.io brings weNotice that socket.io has also implementations server side for Java, C#, Android, etc). Installation of NodeJS and of the express and socket.io modules Go to http://www.nodejs.org and install the last version of NodeJS. Click on the install button on the web page. Check the installation. Open a terminal window, type "node --version", this should print something like: "node 0.10.x". Test of a first NodeJS application Create somewhere a file names test.js, with this content
var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');
Save and run this command from the terminal: node test.js You just ran your first nodeJS application, try it with a Web browser by opening: http://localhost:8124 You should see this in your web browser: The test.js file contains ultra minimal code for creating and configuring an HTTP web server. This ultra minimal server answers requests by sending string responses on the fly. If we want to serve HTML files, images, JS files, CSS files, we need a more complete web server. This is what the "express" module will bring to NodeJS. And we will also need the socket.io module for using WebSockets. NodeJS module installation We will use the "npm" (node package manager) command from the nodeJS installation Create a directory named "chatWithSocketIO" somewhere cd in it, run "npm install express", run "npm install socket.io". You should see a subdir named "node_modules" that contains the new modules you just downloaded/installed locally to your project. Simple chat application that uses express and socket.io This part is an updated/fixed version of this tutorial , that explains how to write a small chat application with nodeJS, express and socket.io. We cleaned the code and adapted it so it works with the last version of express (v3), and socket.io. Get this archive : chatSocketIO.rar Unarchive it in your working dir. You should get this; Now run this command "node simpleChatServer.js" and open "http://localhost:8080", in your browser. Open th URL in two different tabs. Enter two different names, try to chat, look at what happens in the different tabs.Open Chrome dev tools, you should find how to trace data exchanged over web sockets. Now, study the code of simpleChatServer.js, of simpleChat.html, and read : http://psitsmike.com/2011/09/node-js...chat-tutorial/, forget the beginning about the nodeJS installation, just read the code explanations. socket.io basic principles socket.on(event_name, callback) : executes the callback when an event with a given name is fired. (event_name = user defined). Some events like 'connection' or 'disconnect' are predefined. All event processing is performed in the io.sockets.on('connection', function (socket) {...}, call. socket.emit(event_name, data1, data2): sends only to the connected client the event and two parameters with data io.sockets.emit(event_name, data1, data2): same but sends to all connected clients socket.broadcast.emitevent_name, data1, data2): same but sends to all connected clients except the emitter simpleChatServer.js:
// We need to use the express framework: have a real web server that knows how to send mime types etc.
var express=require('express');

// Init globals variables for each module required
var app = express()
  , http = require('http')
  , server = http.createServer(app)
  , io = require('socket.io').listen(server);

// Indicate where static files are located  
app.configure(function () {  
    app.use(express.static(__dirname + '/'));  
});  

// launch the http server on given port
server.listen(8080);

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

// usernames which are currently connected to the chat
var usernames = {};

io.sockets.on('connection', function (socket) {

 // when the client emits 'sendchat', this listens and executes
 socket.on('sendchat', function (data) {
  // we tell the client to execute 'updatechat' with 2 parameters
  io.sockets.emit('updatechat', socket.username, data);
 });

 // when the client emits 'adduser', this listens and executes
 socket.on('adduser', function(username){
  // we store the username in the socket session for this client
  socket.username = username;
  // add the client's username to the global list
  usernames[username] = username;
  // echo to client they've connected
  socket.emit('updatechat', 'SERVER', 'you have connected');
  // echo globally (all clients) that a person has connected
  socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected');
  // update the list of users in chat, client-side
  io.sockets.emit('updateusers', usernames);
 });

 // when the user disconnects.. perform this
 socket.on('disconnect', function(){
  // remove the username from global usernames list
  delete usernames[socket.username];
  // update list of users in chat, client-side
  io.sockets.emit('updateusers', usernames);
  // echo globally that this client has left
  socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
 });
});
And simpleChat.html:



USERS
Multiroom chat: several groups of clients can chat together This version enable clients to be in groups called "rooms". The Socket.io API has a complete set of functions for joining/leaving a room, sending messages to all people in a room, to all people except the emitter, etc. socket.join(room_name) and socket.leave(room_name) : when joining a non existing room it creates it, socket.broadcast.to(room_name).emit(...): similar to socket.broadcast.emit, sends a message to all clients in the room except the emitter. io.sockets.inroom_name).emit(...) : sends to all clients in the room. Complete documentation of the room API: https://github.com/LearnBoost/socket.io/wiki/Rooms multiRoomChatServer.js
// We need to use the express framework: have a real web server that knows how to send mime types etc.
var express=require('express');

// Init globals variables for each module required
var app = express()
  , http = require('http')
  , server = http.createServer(app)
  , io = require('socket.io').listen(server);

// Indicate where static files are located. Without this, no external js file, no css...
app.configure(function () {  
    app.use(express.static(__dirname + '/'));  
});  

// launch the http server on given port
server.listen(8080);

// routing with express, mapping for default page
app.get('/', function (req, res) {
  res.sendfile(__dirname + '/multiRoomChat.html');
});

// usernames which are currently connected to the chat
var usernames = {};

// rooms which are currently available in chat
var rooms = ['room1','room2','room3'];

io.sockets.on('connection', function (socket) {
 
 // when the client emits 'adduser', this listens and executes
 socket.on('adduser', function(username){
  // store the username in the socket session for this client
  socket.username = username;
  // store the room name in the socket session for this client
  socket.room = 'room1';
  // add the client's username to the global list
  usernames[username] = username;
  // send client to room 1
  socket.join('room1');
  // echo to client they've connected
  socket.emit('updatechat', 'SERVER', 'you have connected to room1');
  // echo to room 1 that a person has connected to their room
  socket.broadcast.to('room1').emit('updatechat', 'SERVER', username + ' has connected to this room');
  socket.emit('updaterooms', rooms, 'room1');
 });
 
 // when the client emits 'sendchat', this listens and executes
 socket.on('sendchat', function (data) {
  // we tell the client to execute 'updatechat' with 2 parameters
  io.sockets.in(socket.room).emit('updatechat', socket.username, data);
 });
 
 socket.on('switchRoom', function(newroom){
  socket.leave(socket.room);
  socket.join(newroom);
  socket.emit('updatechat', 'SERVER', 'you have connected to '+ newroom);
  // sent message to OLD room
  socket.broadcast.to(socket.room).emit('updatechat', 'SERVER', socket.username+' has left this room');
  // update socket session room title
  socket.room = newroom;
  socket.broadcast.to(newroom).emit('updatechat', 'SERVER', socket.username+' has joined this room');
  socket.emit('updaterooms', rooms, newroom);
 });
 

 // when the user disconnects.. perform this
 socket.on('disconnect', function(){
  // remove the username from global usernames list
  delete usernames[socket.username];
  // update list of users in chat, client-side
  io.sockets.emit('updateusers', usernames);
  // echo globally that this client has left
  socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
  socket.leave(socket.room);
 });
});
multiRoomChat.html



ROOMS
Code explanations here: http://psitsmike.com/2011/10/node-js-and-socket-io-multiroom-chat-tutorial/ (we made small updates to the code) Node.js Tutorial Videos: Part - 1 Part - 2 Part - 3 Part - 4 Part - 5 Part - 6 Part - 7 Part- 8 Part - 9 Part - 10

3 comments:

  1. Hi this is harish. we are working with phone for multiple platforms.now we have a requirement i.e chat between two persons.is it work for mobiles for android and iPhone.Thanks in advance

    ReplyDelete
  2. Why built it yourself when you can have someone built it for you? https://goo.gl/uWY5Cp

    ReplyDelete
  3. If you are looking for phone gap app developers, please contact www.Getpromoted.in

    ReplyDelete