我正在使用MEAN堆栈编写聊天应用程序,但是在实现它们时我遇到了困难。服务器没有从客户端获得任何类型的更新,也没有向客户端发送任何内容。我猜服务器中有一些错误,但无法解决任何问题。
server.js文件是: -
(function (exports, require, module, __filename, __dirname) {
var express = require('express'),
neo4j = require('node-neo4j'),
bodyParser = require('body-parser'),
app = express();
//socket io integration
var io = require('socket.io')(3000);
var clients = [];
app.get('/', function (req, res) {
res.sendfile('./index.html');
});
io.on('connection', function (socket)
{
console.log("Server : Connected to Socket IO");
console.info('New client connected (id=' + socket.id + ').');
socket.on('user enter',function(user_name){
clients.push({id:socket.id,userName:user_name});
len=clients.length;
io.emit('user entrance',clients,clients[len-1].id);
});
socket.on('send msg',function(data){
socket.broadcast.to(data.id).emit('get msg',{msg:data.msg,id:data.id,name:data.name});
});
socket.on('disconnect', function(data){
console.log("user disconnected :" +data.id);
})
});
app.use(require("express").static('data'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.set('port', process.env.PORT || 5000);
app.listen(app.get('port'), function () {
applogger.info('Express server listening on port ' + app.get('port'));
});
});
客户端代码(chatController.js)是 -
angular.module('myApp')
.controller('ChatCtrl',function($rootScope, $scope, $stateParams,socket,$ionicScrollDelegate,$timeout) {
$scope.userName = $scope.user.name;
socket.on('connect',function()
{
console.log("from userListCtrl : "+ JSON.stringify($rootScope.selectedUser));
$scope.selected_id=$rootScope.selectedUser;
});
socket.emit('user enter',$scope.userName);
socket.on('user entrance',function(data,my_id){
//checking the user id
if($scope.my_id==null){
$scope.my_id=my_id;
}
$scope.user_show=data;
});
$scope.send_msg = function($event){
var keyCode = $event.which || $event.keyCode;
if($scope.selected_id==$scope.my_id){
alert("You can't send msg to your self.");
}else{
if (keyCode === 13) {
var data={
id:$scope.selected_id,
msg:$scope.msg_text,
name:$scope.userName
};
$scope.msg_text='';
socket.emit('send msg',data);
}
}
};
//Getting the messages from server.
socket.on('get msg',function(data){
$scope.msgs=data;
$scope.is_msg_show=true;
addMessage();
});
// function of push messages to an array.
UI部分非常干净,它是您可以单击的用户列表,它将打开一个聊天窗口,这两个用户可以亲自聊天。除了将msg发送到服务器并从中获取响应之外,每个事情都发生在客户端(例如用户详细信息,消息内容等)。 我陷入了困境。