Search code examples
node.jsnginxsocket.iogunicornpm2

Socket.io not working with nginx


I have a nicely working django website which is being served by gunicorn and nginx(as a proxy server), now i want to add chat mechanism in that website using socket.io and nodejs. The problem is that the chat works perfectly fine when i connect socketio directly to nodejs server(which is listening on port 5000) but when i try to use nginx to proxy the socketio request to nodejs it doesn't work.

Here is my nginx file in /sites-enabled/ dir

server {
    listen 80;
    server_name 127.0.0.1;

    location = /favicon.ico {
        access_log off;
        log_not_found off;
    }
    location /static/ {
        root /path/to/static;
    }
    location / {
        include proxy_params;
        proxy_pass http://unix:/path/to/file.sock;
    }

    location /socket.io/ {
        proxy_pass http://127.0.0.1:5000;
        proxy_redirect off;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

BTW I am using pm2 to manage nodejs (if it makes any difference).

EDIT:

server.js:


var io = require('socket.io').listen(5000);
var fs = require('fs');

io.on('connection', function(socket){
    console.log('connected');


    socket.on('question', function(data){
        console.log(data);
        soc.emit('question', data);
    });

    socket.on('advice', function(data){
        console.log(data);
        soc.emit('advice', data);
    });

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




client.js

var socket  = io('http://127.0.0.1/socket.io/');


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


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

$('#send').click(function() {

    var msg     = $('#msg').val();

    if (msg == '') {$('#msg').focus();}
    else{

        data = {msg:msg};
        socket.emit('question', data);

        var msg = $('#msg').val('').focus();
    }  
});

Solution

  • The URL that you're using for the client is incorrect:

    var socket = io('http://127.0.0.1/socket.io/');
    

    Adding a path (in this case, /socket.io/) has a special meaning in connection strings: it reflects the namespace that you want the client to connect to.

    Since you're not using namespaces, you should leave it off:

    var socket = io('http://127.0.0.1/');
    // Or possibly even just this:
    // var socket = io();