Thursday 20 April 2017

Socket.io - angularjs connects to the server, i see the logs, but i cannot emit anything

I am using nodejs and angularjs in a Nginx together with socket.io but i am struggling to emit any messages an listen to events.

I played around a lot configuring nginx based on nginx-socket.io suggested settings.

When connecting from client side, i see the logs into the server. I am connecting like this

 var socket = io.connect('https://myserver.com/socket.io', { 'transports': ['websocket', 'polling', 'xhr-polling'] });

This is some part of the server side code:

var app = express();
var httpServer = http.createServer(app);

httpServer.listen(port, function() {
    console.log('Running on port ' + port + '.');
});

var io = require('socket.io').listen(httpServer);

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

    console.log('======= a user connected =======');

    socket.emit('welcome', { message: 'Welcome!' });

    socket.on('enterRoom', function (data) {
        console.log(data);
    });

    socket.on('disconnect', function(){
        console.log('++++++++ user disconnected ++++++++');
    });
});

I have the following factory right after my connection:

    return {
    on: function(eventName, callback) {
        socket.on(eventName, function() {
            var args = arguments;
            console.log(args);
            $rootScope.$apply(function() {


                callback.apply(socket, args);
            });
        });
    },
    emit: function(eventName, data, callback) {
        socket.emit(eventName, data, function() {
            var args = arguments;
            console.log(args);
            $rootScope.$apply(function() {
                if (callback) {
                    callback.apply(socket, args);
                }
            });
        });
    }
};

Then i inject my factory 'socketio' into my controller, and try to lister/communicate with my server.

Part of controller code:

socketio.on('connect', function() {
    socketio.on('welcome', function (data) {
      console.log(data);
      socketio.emit('enterRoom', { my: 'data' });
    });
});

When refreshing i always see the "user connected" and "user disconnected" logs into the server logs, but i cannot see anything else besides that.

I have already set the following configurations also:

location /socket.io/ {
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_http_version 1.1;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $host;
    proxy_pass http://localhost:3000;
}



via FotisK

No comments:

Post a Comment