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 
    }

    location / {
        proxy_pass 
        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(');


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();
    }  
});
7

1 Answer

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

var socket = io(');

Adding a path (in this case, /) 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(');
// Or possibly even just this:
// var socket = io();
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest