nginx - Gorilla WebSocket 一分钟后断开连接

标签 nginx go websocket gorilla

我在 nginx 1.4.6 反向代理后面使用 Go (Golang) 1.4.2 和 Gorilla WebSockets。打开页面大约一分钟后,我的 WebSocket 断开连接。在 Chrome 和 Firefox 上也会出现同样的行为。

起初,我在使用 WebSocket 连接服务器和客户端时遇到了问题。然后,我读到我需要调整我的 nginx 配置。这就是我所拥有的。

server {
    listen 80;
    server_name example.com;

    proxy_pass_header Server;

    location / {
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forward-Proto $scheme;

        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        proxy_pass http://127.0.0.1:1234;
    }
}

我的 Go 代码基本上是在回显客户端的消息。 (为简洁起见,省略了错误)。这是我的 HandleFunc

var up = websocket.Upgrader{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
}

ws, _ := up.Upgrade(resp, req, nil)
defer ws.Close()

var s struct {
    Foo string
    Bar string
}

for {
    ws.ReadJSON(&s)
    ws.WriteJSON(s)
}

JavaScript 也很简单。

var ws = new WebSocket("ws://example.com/ws/");
ws.addEventListener("message", function(evnt) {
    console.log(JSON.parse(evnt.data));
});

var s = {
    Foo: "hello",
    Bar: "world"
};
ws.send(JSON.stringify(s));

Go 正在报告 websocket: close 1006 unexpected EOF。我知道当我离开或刷新页面时 ReadJSON 返回 EOF,但这似乎是一个不同的错误。此外,在打开页面大约一分钟后,意外的 EOF 会自行发生。

我在 JavaScript 中有一个 onerror 函数。该事件不会触发,但会触发 onclose

最佳答案

我有同样的问题,问题是 nginx 配置。 proxy_pass 默认为 1 分钟读取超时:

Syntax: proxy_read_timeout time;

Default: proxy_read_timeout 60s;

Context: http, server, location

http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_read_timeout

就我而言,我已将超时时间增加到 10 小时:

proxy_read_timeout 36000s;

关于nginx - Gorilla WebSocket 一分钟后断开连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28828332/

相关文章:

python - uwsgi:什么定义了 django 应用程序需要的 worker /进程的数量?

nginx - 在 NGINX OSS 中编译 ModSecurity

nginx - 如何防止谷歌索引我的 https 网址?

go - 如何访问另一个结构内的 golang 结构数组?

json.Marshal 与 Encoder.Encode

go - 如何让每个眼镜蛇命令解析自己的标志?获取初始化循环(预期,但如何避免?)

Java : Opening client socket

express - 将nginx与expressJS结合使用时,我应该在express还是nginx中使用压缩?

tomcat - 是否有在 JBoss AS7 中使用 WebSockets 的示例?

javascript - 为 Dart 二进制 websocket 从 ByteBuffer 读取/写入固定大小的 int 和字符串