我使用Go(Golang)1.4.2和Gorilla WebSockets在nginx 1.4.6反向代理後面。打開頁面大約一分鐘後,我的WebSockets斷開連接。 Chrome和Firefox出現同樣的行爲。大猩猩WebSocket在一分鐘後斷開連接
起初,我在使用WebSockets連接服務器和客戶端時遇到問題。然後,我讀到我需要調整我的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));
走的是報告websocket: close 1006 unexpected EOF
。我知道當我離開或刷新頁面時ReadJSON
返回EOF
,但這似乎是一個不同的錯誤。此外,在頁面打開約一分鐘後,意外的EOF本身也會發生。
我在JavaScript中有一個onerror
函數。該事件不會觸發,但是onclose
會發生。
到目前爲止好,你永遠不知道,什麼時候會跟你分享一些智慧。多謝,夥計! – 2015-05-09 12:21:42
@MaxYari夥計庇護 – 2015-05-09 15:20:57