dongqiao9583 2015-03-03 09:34
浏览 736
已采纳

一分钟后,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条回答 默认 最新

  • dongxuan2577 2015-03-03 10:51
    关注

    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;

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题