How do I get socket.io running for a subdirectory

前端 未结 4 1865
广开言路
广开言路 2021-02-02 10:46

I\'ve got a proxy running that only hits my node.js server for paths that being with /mysubdir How do I get socket.io configured for this situation?

In my c

相关标签:
4条回答
  • 2021-02-02 11:04

    In my server I had to

    var io = require('socket.io')(httpServer, {path: '/mysubdir/socket.io'})`
    

    In my client I had to

    <script src="http://www.example.com/mysubdir/socket.io/socket.io.js"></script>
    

    and also

    var socket = io.connect('http://www.example.com', {path: "/mysubdir/socket.io"});`
    
    0 讨论(0)
  • 2021-02-02 11:06

    Using nginx, this a solution without the need to change anything in the socket.io server app:

    In the nginx conf:

    location /mysubdir {
       rewrite ^/mysubdir/(.*) /socket.io/$1 break;
       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://127.0.1.1:3000;
    }
    

    In the server:

    var io = require('socket.io')(3000)
    

    In the client:

    var socket = io.connect('https://example.com/', {
        path: "/mysubdir"
    })
    
    0 讨论(0)
  • 2021-02-02 11:23

    In my case I am using nginx as a reverse proxy. I was getting 404 errors when polling. This was the solution for me.

    The url to the node server is https://example.com/subdir/

    In the app.js I instantiated the io server with

    var io = require('socket.io')(http, {path: '/subdir/socket.io'});
    

    In the html I used

    socket = io.connect('https://example.com/subdir/', {
        path: "/subdir"
    });
    

    Cheers,
    Luke.

    0 讨论(0)
  • 2021-02-02 11:27

    The answer by @Drew-LeSueur is correct for socket.io >= 1.0.

    As I was using socket.io 0.9, I found the old way of doing it in the doc.

    // in 0.9
    var socket = io.connect('localhost:3000', {
      'resource': 'path/to/socket.io';
    });
    
    // in 1.0
    var socket = io.connect('localhost:3000', {
      'path': '/path/to/socket.io';
    });
    

    Notice that a / appears as first character in the new path option.

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