M
M
Mikhailo Poberezhny2016-03-30 17:16:13
Angular
Mikhailo Poberezhny, 2016-03-30 17:16:13

join and leave not working in socket.io node?

server.js

var express = require('express');
var http = require('http');
var path = require('path');
var config = require('config');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var busboyBodyParser = require('busboy-body-parser');
var cookieParser = require('cookie-parser');
var methodOverride = require('method-override');
var errorHandler = require('express-error-handler');
var fs = require('fs');
var connect = require('connect');
var app = express();
var server = http.createServer(app);
var io = require('socket.io')(server);
var async = require('async');

app.engine('html', require('hogan-express'));

app.set('views', __dirname + '/public');

app.set('view engine', 'html');
app.set('view options', {
    layout: true
});
app.set('layout', 'layout');
app.enable('view cache');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(busboyBodyParser());
app.use(cookieParser());
app.use(methodOverride());

app.use(express.static(path.join(__dirname, 'public')));

if ('development' == app.get('env')) {
    app.use(errorHandler());
    mongoose.connect('mongodb://31.131.22.106/sockets');
}

var sessionMiddleware = session({
    //store: new RedisStore({}),
    secret: "keyboard cat"
});

io.use(function(socket, next) {
    sessionMiddleware(socket.request, socket.request.res, next);
});

app.use(sessionMiddleware);

var sess;

fs.readdir(__dirname + '/routes', function(err, name) {
    name.forEach(function(filename) {
        if (~filename.indexOf('.js')) require(__dirname + '/routes/' + filename)(app, sess);
    })
});

app.get('/', function(req, res) {
    sess = req.session;
    res.render("./public/index");
});

app.get('/session', function(req, res) {
    req.session = sess;
    res.json(req.session);
});

var rooms = [ 'room1', 'room2', 'room3' ];

io.sockets.on('connection', function(client) {

    console.log('- client connected...');
    // models
    var module = require('./modules/socket.js');

    var messageItem = function (who, to, message){
        this.who = who;
        this.to = to;
        this.message = message
    };

    client.emit('rooms', rooms);

    client.on('new user', function(name) {
        client.join('room1');
        module.checkUser(name, function(err, user) {
            client.username = user.name;
            client.id = user._id;
            client.room = user.currentRoom;
            var toRoom = user.name + ' has connected to this room [' + user.currentRoom + ']';
            var messageToRoom = new messageItem(user.name, user.currentRoom, toRoom);
            client.broadcast.to(user.currentRoom).emit('to chat', messageToRoom);
            client.emit('created user', {
                room: user.currentRoom,
                name: user.name
            });
        });
    });

    client.on('message', function(message) {
        var messageToRoom = new messageItem(client.username, client.room, message.message);
        console.log('message to: ', message.room);
        console.log(client.rooms);
        io.in(message.room).emit('to chat', messageToRoom);

        module.saveMessage({id: client.id, name: client.username}, message, function(err, result) {
        });
    });

    client.on('change_room', function(room) {

        client.leave(client.room);
        client.room = room;
        client.join(room);
        console.log(client.rooms);

        var messageToRoom = new messageItem(client.username, client.room,
            client.username + ' left the room [' + client.room +']');
        client.broadcast.to('room1').emit('to chat', messageToRoom);

    });

    client.once('disconnect', function () {
        console.log('- client [' + client.id + '] disconnected!');
    });

});


server.listen(3000, function() {
    console.log('Server listening on port ' + 3000);
});


client (app.js)

.controller('authorizationCtrl', ['$scope', '$state', 'authorization', 'socket', 'storage', function($scope, $state, authorization, socket, storage) {

      $scope.rooms = ['room1', 'room2', 'room3'];
      $scope.messages = [];
      $scope.userRoom = '';
      $scope.userName = '';

      socket.on('connect', function(){
        console.log('[front-end] client connected...');
      });

      //socket.on('rooms', function(rooms) {
      //  $scope.rooms = rooms;
      //});

      socket.on('created user', function(user){
        $scope.userRoom = user.room;
        $scope.userName = user.name;
      });

      socket.on('to chat', function(message){
        console.log(message);
        $scope.messages.push(message);
      });

      $scope.newUser = function() {
        socket.emit('new user', $scope.auth.name);
      };
      // add new message
      $scope.sendMessage = function() {
        var message = {
          message: $scope.message,
          room: $scope.userRoom
        };
        socket.emit('message', message);
      };

      $scope.switchRoom = function(room) {
        $scope.userRoom = room;
        socket.emit('change_room', room);
      };

    }]);

"change_room" does not work, it's just that the socket in room 1 (room1) is always and does not change, tell me what's wrong.
In html there are 3 buttons respectively room1, room2, room3 when I click on the button, the
"switchRoom" function is called and passes the name of the room there. Everything comes to the server via "client.on -> change_room" but simply does not assign it to the socket itself.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question