如何使用Express,AngularJS,Socket.io广播和获取通知?

我正在尝试通知系统。 为了演示这一点,用户1正在向用户2发送好友请求。我正在使用express.js,angularjs和socket.io。 点击buttonUser1发送请求。 在User2的最后,有一个socket,on()正在监听好友请求事件。 但是当我广播时,另一个用户不能接收任何消息。

app.js (节点服务器文件)

var express = require('express'), app = express(); var port = process.env.PORT || 3000; var io = require('socket.io').listen(app.listen(port)); require('./config')(app,io); require('./routes')(app,io); 

config.js

 // This file handles the configuration of the app. // It is required by app.js var express = require('express'); module.exports = function(app, io){ // Set .html as the default template extension app.set('view engine', 'html'); // Initialize the ejs template engine app.engine('html', require('ejs').renderFile); // Tell express where it can find the templates app.set('views', __dirname + '/views'); // Make the files in the public folder available to the world app.use(express.static(__dirname + '/public')); }; 

routes.js (从此文件中发送朋友请求)

 var gravatar = require('gravatar'); var mysql = require('mysql'); // This is needed if the app is run on heroku: var connection = mysql.createConnection({ host : "localhost", user : "root", password : "", database : "two_way_demo" }); connection.connect(function(error){ if(error) { console.log("Problem with MySQL"+error); } else { console.log("Connected with Database"); } }); module.exports = function(app,io){ app.get('/',function(req,res){ res.render('index'); }); app.get('/create', function(req,res){ // Generate unique id for the room var id = Math.round((Math.random() * 1000000)); // Redirect to the random room res.redirect('/chat/'+id); }); app.get('/home/:id', function(req,res){ // Render the chant.html view res.render('home'); }); // Initialize a new socket.io application, named 'chat' var chat = io.on('connection', function (socket) { socket.on('get-user-id',function(data){ connection.query("SELECT * from user_info WHERE email='"+data.userEmail+"'",function(err,rows){ if(err) { console.log("Problem with MySQL"+err); } else { //console.log(rows); JSON.stringify(rows); socket.emit('user-id',rows); } }); }); socket.on('send-request',function(data){ console.log(data); ********************************************************************* // Tried the emit here but its not working //io.emit('friend request', { // receiverid: data.receiverid //}); ********************************************************************* }); }); } 

angular-code.js (angular码文件)

 $(function () { var app = angular.module("notificationApp", []); app.controller("chatCTRL", ["$scope", "$http", "$interval", function ($scope, $http, $interval) { // connect to the socket //var socket = io(); //socket.on('connect', function () { // io.on('friend request', function (data) { // alert("here") // }); //}); $scope.senderId = Number(window.location.pathname.match(/(\d+)$/)[1]); $scope.sendrequest = function (senderid, receiverid) { var socket = io(); socket.on('connect', function () { socket.emit('send-request', { senderid: senderid, receiverid : receiverid }); }); } }]); app.controller("loginCTRL", ["$scope", "$http", "$interval", "$window", function ($scope, $http, $interval, $window) { $scope.sendLogin = function () { var socket = io(); socket.on('connect', function () { socket.emit('get-user-id', { userEmail: $scope.hisEmail }); }); socket.on('connect', function () { socket.on('user-id', function (data) { $scope.UserId = data[0].user_id; $window.location = "http://localhost:3000/home/" + $scope.UserId; }); }); } }]); }()); 

home.html的

 <!DOCTYPE html> <html ng-app="notificationApp"> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body ng-controller="chatCTRL"> <h1>welcome</h1> <div id="createbutton"> <div id="little"><button ng-click="sendrequest(senderId,6)">Send Friend Request to User#6</button></div> </div> <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="/socket.io/socket.io.js"></script> <script src="../angular/angular.js"></script> <script src="../angular/common_angular.js"></script> </body> </html> 

一些客户端架构的东西:

  1. 在大多数angular度客户端的情况下,最好将您的套接字连接移动到服务。 并且在服务初始化的时候build立连接(服务是单例的,因此启动时会有一个连接)并且在你的控制器中注入这个服务。
  2. 创build一些具有所有套接字侦听器的父抽象控制器可能会比较方便,因此无论angular度控制器是否处于活动状态,所有侦听器都在观看。 当父控制器从套接字获取数据时,可以将其广播给儿童控制器

在你的评论代码中你有:

  //var socket = io(); //socket.on('connect', function () { // io.on('friend request', function (data) { // alert("here") // }); //}); 

将其更改为(如果在服务中进行连接,则应省略连接部分):

  var socket = io(); socket.on('connect', function () { socket.on('friend request', function (data) { alert("here") }); }); 

后端:

在你的评论代码中你有:

 //io.emit('friend request', { // receiverid: data.receiverid //}); 

你应该使用socketvar chat = io.on('connection', function (socket) {...发射而不是io.emit

创build数组variables,您将在连接部分之前将所有套接字与用户标识一起存储:

 var socketList = []; var chat = io.on('connection', function (socket) { socketList.push({id:someId,socket:socket}) ... } 

现在在send-request用户应该发送他的简历(我们必须知道哪个用户应该被通知 – 当然,我们可以通知大家):

 socket.on('send-request',function(data){ socketList.forEach(function(soc){ if(soc.id === someId){ soc.socket.emit('friend request', { receiverid: data.receiverid }) } }); 

我也不喜欢这部分receiverid: data.receiverid ,因为这意味着taget用户从接收方客户端获得接收者的id。 这可能是不安全的(用户可以改变他的ID并发送一些其他的ID)。 我优先考虑在服务器端创buildid,当用户A向用户BI发送通知时,从服务器variables中获取用户A的id。

有些时候,我创build了一个简单的聊天应用程序原型(angular色和expression),我在这里提到了一些东西。 我还有问题,你的应用程序去那里检查我的代码: https : //github.com/uhlryk/chat-prototype