Showing posts with label Node js. Show all posts
Showing posts with label Node js. Show all posts

Saturday, December 10, 2016

Make A Real-Time Chat Room using Node Js Server and Socket.io

Start using node js follow link

Download full code example from here



var http = require('http'),
    connect = require('connect'),
    express = require('express'),
    app = express(),
    ent = require('ent'),
    server = http.createServer(app),
    io = require('socket.io').listen(server);

app.use(express.bodyParser());

app.get('/', function (req, res) {
    res.sendfile(__dirname + '/login.htm');
});
app.get("/login", function(req, res) {
    res.writeHead(302, {Location: '/'} );
    res.end();
});
app.post("/login", function(req, res) {
    var userName = "", group = "";
    try { userName = ent.decode(req.body.userName).trim(); } catch(e) {}
    try { group = ent.decode(req.body.group).trim(); } catch(e) {}
    if(userName.length == 0) {
        res.writeHead(302, {Location: '/?Error=Need User Name'} );
        res.end();
        return;
    }
    if(group.length == 0) {
        res.writeHead(302, {Location: '/?Error=Need Group'} );
        res.end();
        return;
    }
    res.writeHead(302, {Location: '/chat?UserName=' + userName + "&Group=" + group} );
    res.end();
});
app.get("/chat", function(req, res) {
    res.sendfile(__dirname + '/chat.htm');
});
//Static resource setup
app.use(express.static(__dirname + '/public'));

io.sockets.on('connection', function (socket) {
    socket.on('new_client', function (UserName, Group) {
        socket.UserName = UserName;
        socket.Group = Group;
        socket.join(Group);
        console.log(UserName + " connected on group=" + Group);
        socket.broadcast.to(socket.Group).emit('message', {UserName: UserName, message: " Connected!!!"});
    });

    socket.on('message', function (message) {
        socket.broadcast.to(socket.Group).emit('message', {UserName: socket.UserName, message: ent.encode(message)});
    });

    socket.on('disconnect', function() {
        try {
            if(socket.UserName !== undefined) {
                socket.broadcast.emit('message', {UserName: socket.UserName, message: " Disconnected!!!"});
            }
        }
        catch(ex) { }
    });
});

var PORT = 9999;
server.listen(PORT, function () {
    //Callback triggered when server is successfully listening.
    console.log("Server listening on: http://localhost:%s", PORT);
});



Wednesday, December 7, 2016

First HTTP Server in Node.js

1. Download node server from here or here and extract to a local folder
2. Download NPM (Node Package Manager) from here or here and extract to a local folder
3. Configure environment PATH Variable. Open command prompt and do the following:
C:\Users\pritom>set PATH=%PATH%;C:\Users\..\NODE_FOLDER;C:\Users\..\NPM_FOLDER

C:\Users\pritom>echo %PATH%
...;C:\Users\pritom\Desktop\codes\node_1\node-v7.2.1-win-x64;C:\Users\pritom\Desktop\codes\node_1\npm-4.0.5

C:\Users\pritom>node --version
v7.2.1

4. Create a file named "server.js" in a local folder with following contents:



//Lets import the HTTP module
var http = require('http');

//Lets define a port we want to listen to
const PORT = 5555;

//We need a function which handles requests and send response
function handleRequest(request, response) {
    response.end('Node js server browse at: [[http://localhost:' + PORT + request.url + ']]');
}

//Create a server
var server = http.createServer(handleRequest);

//Lets start our server
server.listen(PORT, function () {
    //Callback triggered when server is successfully listening.
    console.log("Server listening on: http://localhost:%s", PORT);
});



5. Now navigate to the folder using command prompt and type "node server.js" will output:
Server listening on: http://localhost:5555

6. Hit "http://localhost:5555" in your browser and see the result.....