我正在制作一个简单的聊天应用程序,其中有房间和用户加入房间并聊天。我没有任何身份验证系统,因此用户是随机的。我发送我在mongodb存储的房间ID,供用户进行加入或离开房间。我的问题是,如果我在一个浏览器中更改房间,其他浏览器中的房间chages。 我打开的两个浏览器都反映了相同的变化。我想我错了,有人可以帮我解决这个问题。
var myApp = angular.module('myApp', []);
myApp.factory('socket', function(){
return io.connect('http://localhost:3000');
});
myApp.controller('controller', function($scope, $http, $timeout, socket){
$scope.rooms = [];
$scope.messages = [];
$scope.name;
$scope.roomId ;
socket.emit('get Rooms', {});
socket.on('got rooms', function(data) {
$scope.rooms = data.rooms;
$scope.$digest();
});
$scope.addRoom = function() {
socket.emit('add Rooms', {roomName : $scope.roomName});
};
$scope.changeRoom = function(id) {
console.log(id);
socket.emit('change Room', $scope.roomId, id);
socket.on('room changed', function(data) {
$scope.roomId = data._id;
socket.emit('sent Msg', $scope.roomId);
socket.on('get Msg', function(data) {
$scope.messages = data;
$scope.$digest();
});
});
};
// Adding Users name for first time
$scope.addName = function(name) {
$scope.name = name;
socket.emit('user joined', name);
socket.on('default group', function(data) {
$scope.roomId = data._id;
socket.emit('sent Msg', $scope.roomId);
socket.on('get Msg', function(data) {
$scope.messages = data;
$scope.$digest();
});
})
};
$scope.sendMessage = function(msg) {
socket.emit('send msg', msg, $scope.name, $scope.roomId);
socket.on('get Msg', function(data) {
$scope.$digest();
});
};
});
我的nodeJs代码。
io.sockets.on('connection',function(socket){
var roomsNow =[];
var users = [];
socket.on('get Rooms', function(data){
Room.findAllRooms(function(err, doc){
if(err)
res.sendStatus(500);
else if(doc){
_.each(doc, function(data){
roomsNow.push(data)
});
io.sockets.emit('got rooms', {rooms: roomsNow});
}
});
});
socket.on('change Room', function(oldRoom, newRoom){
socket.leave(oldRoom);
socket.join(newRoom);
io.sockets.emit('room changed', newRoom);
});