客户端无法访问socket.io服务器

时间:2020-10-10 22:07:57

标签: javascript node.js nginx socket.io digital-ocean

该项目托管在Digital Ocean上。

在客户端,它会抛出404错误

GET http://134.209.147.204/socket.io/?EIO=3&transport=polling&t=NKKWF-X //404

这是Nginx配置文件

server {
        listen 80;
        root /var/www/html;
        location / {
                proxy_pass http://127.0.0.1:5000; (where the frontend is running)
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
        }
        location /socket/ {
                proxy_pass http://localhost:3001; (where the sockets.io server is running)

        }

}

前端

socket = io('/socket/')

前端和后端均可正常运行,并且可以从浏览器进行访问。

2 个答案:

答案 0 :(得分:1)

我在尝试将 sockets.io 应用程序连接到位于 Apache2 服务器后面的 nodejs 服务器时遇到了同样的问题。我使用 /video/ 访问 nodejs。我读了这个答案并没有得到它。骗我!但以防万一我不是一个人,我会尝试在这里进一步澄清。

我最终不得不遵循 sockets.io 的代码来理解它们在文档中的含义。我真是个哑巴。文档说:

<块引用>

为指定的命名空间返回一个新的 Socket 实例 URL 中的路径名,默认为 /。例如,如果网址是 http://localhost/users,将建立传输连接到 http://localhost 和 Socket.IO 连接将被建立到 /用户

遵循代码后,含义(在我的假人脑海中)变得清晰。套接字连接是使用我在 socket=io("url/video/") 中指定的“String”建立的,但传输连接将仅尝试其“url”部分。要更改传输连接路径,您需要为 Manager 类指定文档中描述的选项之一,这些选项与 io 类的选项相同。

Here 是相关文档的链接,您需要阅读 io 和 Manager 标题。

答案 1 :(得分:0)

经过几天的黑客入侵,我能够使它正常工作!

nginx配置

upstream websocket {
    server 127.0.0.1:3001;
}

server {
    listen 80;
    root /var/www/html;
    location / {
        proxy_pass http://127.0.0.1:8080;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }

    location /ws/ {
        proxy_pass http://websocket/socket.io/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

socket.io服务器

const app = require('express')();
const server = app.listen(3001);
const io = require('socket.io').listen(server);

socket.io客户端

 socket = io.connect('http://yourdomain/', {path: '/ws/'})