Using socket.io with nodejs on a server with apache as a reverse proxy

前端 未结 3 410
执笔经年
执笔经年 2021-01-02 06:08

I\'m attempting to use Node.js with Socket.IO to faciliate messaging between the browser and client, following the guide.

However, I had to setup Node reverse-proxie

相关标签:
3条回答
  • 2021-01-02 06:48

    This ended up being a multi-pronged solutions.

    First, on the server end of things, I had to set up the endpoints like this

    var io = require('socket.io').listen(8080);
    
    var rootSockets = io.of('/nodejs').on('connection', function(socket)
    {
      // stuff
    });
    
    var otherSockets = io.of('nodejs/other').on('connection', function(socket)
    {
      // stuff
    });
    

    Then, on the client-side, to properly connect looks like this

    var socket = io.connect(
        'http://example.com/nodejs/'
      , {resource: 'nodejs/socket.io'}
    );
    
    // The usage of .of() is important
    socket.of('/nodejs').on( 'event', function(){} );
    socket.of('/nodejs/other').on( 'event', function(){} );
    

    After this, it all worked. Remember, on this server Apache is proxying example.com/nodejs to port 8080 internally.

    0 讨论(0)
  • 2021-01-02 06:52

    I don't think this has anything to do with your apache proxy, but some 'quirks' with how socket.io handles requests on a sub-directory. See my answer here. NGINX configuration to work with Socket.IO

    Basically, you need to use this connect statement instead:

    var socket = io.connect('http://example.com', {resource:'nodejs/socket.io'});

    0 讨论(0)
  • 2021-01-02 07:02

    If anybody is interested, only this worked for me. Replace port 3000 with your Nodejs port

    Apache 2.2.14 inside your VirtualHost

        <IfModule mod_proxy.c>
          <Proxy *>
            Order allow,deny
            allow from all
          </Proxy>
        </IfModule>
    
        RewriteEngine on
    
        RewriteCond %{QUERY_STRING} transport=polling
        RewriteRule /(.*)$ http://localhost:3001/$1 [P]
    
        ProxyRequests off
        ProxyPass /socket.io/ ws://localhost:3001/socket.io/
        ProxyPassReverse /socket.io/ ws://localhost:3001/socket.io/
    

    Client side connection:

      var myIoSocket = io.connect($location.protocol() + '://' + $location.host(), {path: '/socket.io'});
    

    No need to change anything on Node.js side.

    0 讨论(0)
提交回复
热议问题