Showing posts with label Node Chat Example. Show all posts
Showing posts with label Node Chat Example. 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);
});