Search code examples
javascriptnode.jsraspberry-pisocket.iolighty

Can't access to socket.io.js on Raspberry Pi with Lighttpd [Node.JS & Socket.IO]


I'm completely new to Node.JS and Socket.IO since yesterday.

I try to make Node.JS and Socket.IO work on my Raspberry Pi but it doesn't seem to. I can't access to <myip>:1337/socket.io/socket.io.js. I have followed this tutorial so my Lighttpd.conf file seems like so:

$HTTP["host"] == "<myURLtomywebsite>" {
    proxy.server = (" " => ((
        "host" => "<myIP>",
        "port" => 1337)
    )
)

My server.js look like so:

var http = require('http');

httpServer = http.createServer(function(req, res) {
    res.end('Hello World!');
});

httpServer.listen(1337);

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

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

    socket.on('disconnect', function(data) {
        --clients;
        io.sockets.emit('disusr', clients);
    });

    io.sockets.emit('newusr', clients);
});

And I bind to the disusr and newusr events in my client.js to display the number of connected users in a div.

Everything looks fine on my localhost but, in production environment, I cannot link to my socket.io.js file on the 1337 port. To be honest, I'm not even sure what address to use? (URL of my website appended with :1337, localhost, some other address I would have created?)

Any help would be much appreciated. Thanks!


Solution

  • I resolved my problem!

    I linked socket.io.js like so : <script type="text/javascript" src="/socket.io/socket.io.js"></script>

    I used HAProxy instead of Lighttpd mod_proxy as specified in this question

    Here is my conf file (amend <...> per your configuration):

    # this config needs haproxy-1.1.28 or haproxy-1.2.1
    
    global
      log  127.0.0.1  local0
      log  127.0.0.1  local1 notice
      maxconn  4096
      uid  99
      gid  99
      daemon
    
    defaults
      log   global
      mode  http
      option  httplog
      option  dontlognull
      retries  3
      option http-use-proxy-header
      option  redispatch
      option  http-server-close
      maxconn  2000
      contimeout  5000
      clitimeout  50000
      srvtimeout  50000
    
    frontend public
      bind *:80
      acl is_example hdr_end(host) -i <URL.toyourwebsite.com>
      acl is_websocket hdr(Upgrade) -i WebSocket
      acl is_websocket path_beg -i /websockets
      use_backend ws if is_websocket is_example
      default_backend www
    
    backend ws
        balance roundrobin
        option forwardfor # This sets X-Forwarded-For
        timeout queue 5000
        timeout server 86400000
        timeout connect 86400000
        server apiserver localhost:<PORT> weight 1 maxconn 1024 check
    

    And I made Lighttpd listened to the 8080 port (otherwise HAProxy wouldn't start).

    Remind there is no need to use mod_proxy as it is known to be not compatible with websockets. Use HAProxy instead.