我有一个应用程序,我正在尝试为客户建立一个队列系统.我正在尝试这样做,以便当一个客户加入队列时,它会通知商店员工加入,让他们知道加入并尽快帮助客户.
不过,我似乎无法让Socket IO与我的前端交谈.
这是我的代码,我甚至无法让Node将Socket识别为库.我已经遵循了3个不同的教程,并尝试了所有这些,但我无法看到我的服务器代码中出错了什么.
这是我在服务器上与Socket.io相关的内容
var express = require('express'); var app = express(); var io = require('socket.io'); io.on('connection',function(socket){ socket.emit('connection',"Connection created.") console.log("Socket.io is GO"); socket.on('add customer',function(customer){ console.log("Customer added",customer); }) socket.on('notification',function(data) { console.log("NEW CUSTOMER IN THE QUEUE",data); }); });
我似乎无法在我的服务器上运行它,当它运行DID时,它没有显示我在那里的任何socket.on事件,它不会console.log任何东西.
我究竟做错了什么?有没有人成功地让Socket与Express和Angular一起玩得很好?
看起来你的代码不完整或者你没有很好地实现.
原文链接:https://www.f2er.com/angularjs/140749.html我创建了一个使用angular.js,express和socket.io尝试复制您的需求的示例.
这是我的服务器,app.js:
var express = require('express'); var app = express(); var server = require('http').Server(app); var io = require('socket.io')(server); app.use(express.static(__dirname + '/public')); io.on('connection',function(socket) { console.log('new connection'); socket.on('add-customer',function(customer) { io.emit('notification',{ message: 'new customer',customer: customer }); }); }); server.listen(4041,function() { console.log('server up and running at 4041 port'); });
公共/ index.html的
<!doctype> <html ng-app="sampleApp"> <head> </head> <body ng-controller="IndexController"> <label>Please enter your name: </label> <input ng-model="currentCustomer.name"/> <button ng-click="join()">Join</button> <br/> <h1>New Customers: </h1> <ul> <li ng-repeat="customer in newCustomers">{{customer.name}}</li> </ul> <script src="https://cdn.socket.io/socket.io-1.3.5.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.1/angular.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.1/angular-route.js"></script> <script src="app.js"></script> </body> </html>
公共/ app.js
var app = angular.module('sampleApp',['ngRoute']); app.config(['$routeProvider',function($routeProvider) { $routeProvider.when('/',{ templateUrl: '/index.html' }); }]); app.factory('socket',['$rootScope',function($rootScope) { var socket = io.connect(); return { on: function(eventName,callback){ socket.on(eventName,callback); },emit: function(eventName,data) { socket.emit(eventName,data); } }; }]); app.controller('IndexController',function($scope,socket) { $scope.newCustomers = []; $scope.currentCustomer = {}; $scope.join = function() { socket.emit('add-customer',$scope.currentCustomer); }; socket.on('notification',function(data) { $scope.$apply(function () { $scope.newCustomers.push(data.customer); }); }); });