Friday 7 April 2017

Users sending messages to admin through socket.io

I have a chat application where users send messages to each other(private chat). Now using that i want to create chat application where all the users can send messages to admin individually, how can i do that.

server.js

'use strict';   

const express = require("express");
const http = require('http');
const socketio = require('socket.io');
const bodyParser = require('body-parser');


const routes = require('./utils/routes'); 
const config = require('./utils/config'); 


class Server{

    constructor(){
        this.port =  process.env.PORT || 81;
        this.host = `localhost`;

        this.app = express();
        this.http = http.Server(this.app);
        this.socket = socketio(this.http);
    }

    appConfig(){        
        this.app.use(
            bodyParser.json()
        );
        new config(this.app);
    }

    /* Including app Routes starts*/
    includeRoutes(){
        new routes(this.app,this.socket).routesConfig();
    }
    /* Including app Routes ends*/  

    appExecute(){

        this.appConfig();
        this.includeRoutes();

        this.http.listen(this.port, this.host, () => {
            console.log(`Listening on http://${this.host}:${this.port}`);
        });
    }

}

const app = new Server();
app.appExecute();

routes.js

'use strict';

class Routes{

    constructor(app,socket){
        this.app = app;
        this.io = socket;

        /* 
            Array to store the list of users along with there respective socket id.
        */
        this.users = []; 
    }


    appRoutes(){

        this.app.get('/', (request,response) => {
            response.render('index');
        });

    }

    socketEvents(){

        this.io.on('connection', (socket) => {

            socket.on('username', (userName) => {

                this.users.push({
                    id : socket.id,
                    userName : userName
                });

                let len = this.users.length;
                len--;

                this.io.emit('userList',this.users,this.users[len].id); 
            });

            socket.on('getMsg', (data) => {
                socket.broadcast.to(data.toid).emit('sendMsg',{
                    msg:data.msg,
                    name:data.name
                });
            });

            socket.on('disconnect',()=>{

                for(let i=0; i < this.users.length; i++){

                    if(this.users[i].id === socket.id){
                        this.users.splice(i,1); 
                    }
                }
                this.io.emit('exit',this.users); 
            });

        });

    }

    routesConfig(){
        this.appRoutes();
        this.socketEvents();
    }
}
module.exports = Routes;

index.html

<html ng-app="app"  ng-controller="app">
    <head>
        <title>Sending message to specific client</title>
        <link rel="stylesheet" href="css/bootstrap.min.css">
        <link rel="stylesheet" href="css/style.css">
    </head>
    <body>
        <div class="container">
            <div class="row">
                <div class="col-md-4 user-list">
                <h2>List of Users</h2>
                <ul class="list-group">
                    <li class="list-group-item" 
                        ng-repeat="user in userList"
                        ng-class="{ 'active' : user.id == selectedUser}"
                        ng-click = seletedUser(user.id);
                        ng-style="{
                            'cursor': user.id === socketId ? 'not-allowed' :'pointer'
                        }"
                        >
                        <span id='' ></span>
                    </li>
                </ul>

                </div>
                <div class="col-md-8 message-box">
                    <h2>Messages sent by users</h2>
                    <div class="message-container">
                        <ul class="list-group">
                            <li class="list-group-item" 
                                ng-repeat="message in messages"
                                >
                                 says: 
                            </li>
                        </ul>
                        <div class="alert alert-warning" ng-show='messages.length == 0'>
                            No messages for you.
                        </div>
                    </div>
                    <div class="message-sender">
                        <textarea class="form-control" ng-model='message' ng-keypress="sendMsg($event)"></textarea>
                    </div>
                </div>
            </div>
        </div>
    </body> 

    <script src="/socket.io/socket.io.js"></script>
    <script src="js/angular.min.js"></script>
    <script src="js/script.js"></script>
</html>

config.js

class Config{

    constructor(app){
        // Setting .html as the default template extension
        app.set('view engine', 'html');

        // Initializing the ejs template engine
        app.engine('html', require('ejs').renderFile);

        // Telling express where it can find the templates
        app.set('views', (__dirname + '/../views'));

        //Files 
        app.use(require('express').static(require('path').join('public_data')));

    }
}
module.exports = Config;



via akhil reddy

No comments:

Post a Comment