一分钟后,Gorilla WebSocket断开连接

I'm using Go (Golang) 1.4.2 with Gorilla WebSockets behind an nginx 1.4.6 reverse proxy. My WebSockets are disconnecting after about a minute of having the page open. Same behavior occurs on Chrome and Firefox.

At first, I had problems connecting the server and client with WebSockets. Then, I read that I needed to tweak my nginx configuration. This is what I have.

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;
    }
}

My Go code is basically echoing back the client's message. (Errors omitted for brevity). This is my 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)
}

The JavaScript is pretty simple as well.

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 is reporting websocket: close 1006 unexpected EOF. I know that when I leave or refresh the page ReadJSON returns EOF, but this appears to be a different error. Also, the unexpected EOF happens by itself after about a minute of having the page open.

I have an onerror function in JavaScript. That event doesn't fire, but onclose fires instead.

1个回答



我遇到了同样的问题,问题在于nginx配置。 默认情况下, proxy_pass </ code>的读取超时为1分钟:</ p>


语法:proxy_read_timeout time; </ p>

默认值:proxy_read_timeout 60s; </ p>

上下文:http,服务器,位置</ p>
</ blockquote>

请参见 http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_read_timeout </ p> \ n

对于我来说,我已将超时时间增加到10小时:</ p>

proxy_read_timeout 36000s; </ code> </ p>
</ div>

展开原文

原文

I had the same issue, the problem is the nginx configuration. It defaults to a 1 minute read timeout for proxy_pass:

Syntax: proxy_read_timeout time;

Default: proxy_read_timeout 60s;

Context: http, server, location

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

In my case I've increased the timeout to 10 hours:

proxy_read_timeout 36000s;

dongyi8383
dongyi8383 花花公子
5 年多之前 回复
duanni5726
duanni5726 到目前为止一切都很好,您永远不会知道,什么时候花花公子会与您分享一些智慧。 多谢,伙计!
5 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问