如何使用angular.js,socket.io,node.js

时间:2015-09-15 21:40:03

标签: javascript angularjs node.js socket.io

我正在尝试使用AngularJS和Socket.io构建聊天应用程序 我的任务状态是发送和接收来自不同用户的消息。用户必须输入他们的名字才能访问聊天框。显示的消息与mongo终端中的用户对应。

问题是我想在聊天框旁边的列表中显示活动用户,而在聊天主体中我想要显示与相应用户的消息。

代码:index.html

<!DOCTYPE html>
<html ng-app='chatApp'>

<head>
    <title>Socket.IO chat</title>
    <link rel="stylesheet" href="/css/bootstrap.min.css" />
    <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
    <script src="/socket.io/socket.io.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
    <script src="/angularfiles/chatexpress.js"></script>
    <style>
    .hidden {
        display: none;
    }
    </style>
</head>

<body ng-controller='chatController'>
    <!--<form >-->
    <!--     <p> Enter your name</p>-->
    <!--     <input type="text" ng-model="Myname"/>-->
    <!--    <button ng-show="!$scope.toggle" ng-click="su">Submit</button>-->
    <!-- </form>-->
    <form ng-submit="setName()">
        <input type="text" class="input-block-level" ng-model="Myname" placeholder="Your Name">
        <button class="btn btn-success" ng-show="!$scope.toggle" ng-click="$scope.toggle=true">submit</button>
    </form>
    <div class='container' ng-class="{'hidden':!$scope.toggle}">
        <div class=' row'>
            <div class='col-sm-4 col-md-2'>
                <div>
                    <ul>
                        <h5>Active User</h5>
                        <li ng-repeat="user in userlist">{{$scope.user.name}}
                        </li>
                    </ul>
                </div>
            </div>
            <div class='col-sm-8 col-md-6'>
                <div class='panel panel-success'>
                    <div class='panel-heading'>
                        <span class="label label-success">Movie</span>
                    </div>
                    <div class='panel-body'>
                        <!--<ul id="messages">-->
                        <p ng-repeat="msg in msgs track by $index">{{msg}}</p>
                        <!--</ul>-->
                    </div>
                    <!--<form action="">-->
                    <!--    <input id="m" autocomplete="off" />-->
                    <!--    <button>Send</button>-->
                    <!--</form>-->
                    <div class='panel-footer'>
                        <form name='chatform' data-ng-submit="sendMsg()" <label for="chatform">
                            <h5>Your writing here</h5></label>
                            <input type="text" name="chatinput" class="form-control" id="chatinput" data-ng-model='text' />
                            <!--<button type="submit" class="btn btn-success">submit</button>-->
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!--<script>-->
    <!--    var socket = io.connect();-->
    <!--    $('form').submit(function() {-->
    <!--        socket.emit('chat messages', $('#m').val());-->
    <!--    });-->
    <!--    socket.on('message', function(msg) {-->
    <!--        console.log("testing " + msg);-->
    <!--        $('#messages').append($('<li>').text(msg));-->
    <!--    });-->
    <!--</script>-->
</body>

</html>

控制器代码

var app = angular.module('chatApp', []);
app.factory('socket', function() {
    var socket = io.connect();
    return socket;
})

app.controller('chatController', function($scope, socket) {

    $scope.msgs = [];
    $scope.userlist = [];
    $scope.toggle = false;
    // $scope.Myname='';
    $scope.roomname = '';
    $scope.text = '';
    var info = {};


    $scope.sendMsg = function() {
        //console.log("in send message option");
        console.log($scope.Myname);
        info.name = $scope.Myname;

        info.message = $scope.text;
        info.room = $scope.roomname;
        socket.emit('send msg', info);
        //$scope.text='';

    }

    socket.on('newmsg', function(data) {

        // console.log("in getmessage"+ data);
        $scope.msgs.push(data);
        $scope.$digest();

    });



    socket.on('userlist', function(names) {
        $scope.userlist.push(names);
        // console.log("update"+$scope.userlist.names);

        $scope.$apply();

        console.log("update" + $scope.userlist.names);
    });


    socket.on('connect', function() {


        $scope.setName();

        console.log("in setname")
    })


    $scope.setName = function setName() {
        socket.emit('addedName', $scope.Myname);
        console.log("Emitting from name" + $scope.Myname);
    }
})

服务器端码

var http = require('http');
var path = require('path');

var async = require('async');
var socketio = require('socket.io');
var express = require('express');
var mongoose=require('mongoose');
mongoose.connect('mongodb://localhost/chatexpressdb',function(err)
{
    if(err)
    {
        console.log(err);
    }
    else
    {
        console.log("MongoDB is connected");
    }


});

var chatSchema=mongoose.Schema({
    name:{type:String},
    msg: String,
    room: String,
    time:{type:Date,default:Date.now()}

});


var ChatModel=mongoose.model("Message",chatSchema)




//
// ## SimpleServer `SimpleServer(obj)`
//
// Creates a new instance of SimpleServer with the following options:
//  * `port` - The HTTP port to listen on. If `process.env.PORT` is set, _it overrides this value_.
//
var router = express();
var server = http.createServer(router);
var io = socketio.listen(server);
router.use(express.static(path.resolve(__dirname, 'client')));
router.use(express.static(path.resolve(__dirname,'/bower_components')));
var messages=[];
var sockets=[];
var user=[];


io.on('connection',function(socket)
{
    console.log('User is connected');
   /* socket.on('disconnect',function()
    {
        //console.log('User is disconnected');

    });*/











    socket.on('send msg',function(data)
    {
        console.log('chat message is'+ ':'+data.message);







        var savedMsg=new ChatModel();
        savedMsg.name=data.name;
        savedMsg.msg=data.message;

        savedMsg.save(function(err)
        {
            if(err){
                throw err;

            }
            else
            {

                io.sockets.emit('newmsg' ,data.message);

            }


        });

        //now broadcast part
    //   io.sockets.emit('getmsg' ,data,function(error,callback){
    //         console.log(error);

    //     });
        console.log("next io emit");
    }




    );



    socket.on('addedName',function(Myname)
    {


        console.log("Recieving Name" +Myname);
        socket.set(Myname,String(Myname||'Guest'),function(err){
            if(err)
            {
                throw err;
            }
            else
            {
                 console.log("updating Name"+ Myname);

            updateName();
            }
        })

    });


    socket.on('disconnect', function () {
      sockets.splice(sockets.indexOf(socket), 1);
      updateName();
    });



    // function UpdateName()
    // {
    //     io.sockets.emit('username',chatname);

    // }


    function updateName() {
  async.map(
    sockets,
    function (socket, callback) {
      socket.get('name', callback);
      console.log("setting update")
    },
    function (err, names) {
        if(err)
        {
            throw err;
        }
      broadcast('userlist', names);
    }
  );
}

function broadcast(event, data) {
  sockets.forEach(function (socket) {

              //console.log("setting broadcast");
              socket.emit(event, data);
              console.log("setting broadcast"+data);
              //console.log("setting broadcast");
  });
}






}
);


// function updateName() {
//   async.map(
//     sockets,
//     function (socket, callback) {
//       socket.get('name', callback);
//       console.log("setting update")
//     },
//     function (err, names) {
//         if(err)
//         {
//             throw err;
//         }
//       broadcast('userlist', names);
//     }
//   );
// }


// function broadcast(event, data) {
//   sockets.forEach(function (socket) {

//               socket.emit(event, data);
//               console.log("setting broadcast");
//   });
// }


server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function(){
  var addr = server.address();
  console.log("Chat server listening at", addr.address + ":" + addr.port);
});

1 个答案:

答案 0 :(得分:0)

您需要拥有服务器端用户列表,当用户登录时,他们会被添加,删除掉线/断开连接...

当用户列表更改时,从服务器发送带有完整列表或客户端修改的消息......

在客户端,您需要将更改应用于范围,并应用这些更改以重新呈现相关组件。