dooid3005 2015-09-18 17:13
浏览 2164
已采纳

为什么会收到错误消息“ http:response.Write on hijacked connection”?

I am trying out the gorilla websocket library to get a feel of how websockets work with Go. But I keep getting this error message when I hit refresh button on the browser.

When I reload the web page that I am using to test the websocket, I get these error messages on the Go console:

2015/09/18 19:04:41 websocket: close 1001
2015/09/18 19:04:41 http: response.Write on hijacked connection

The first one is status code for "going away". I am assuming it is because when I hit refresh it goes away from the websocket connection so that makes sense to me.

But then I get an error message that I don't understand. The hijacked one. Why do I get it and what does it mean?

I am running my code on localhost:8080 on a windows machine.

The code I am using:

func wsHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) error {
    conn, err := websocket.Upgrade(w, r, nil, 1024, 1024)
    if err != nil {
        return err
    }
    defer conn.Close()

    for {
        _, msg, err := conn.ReadMessage()
        if err != nil {
            return err
        }
        log.Println(string(msg))
    }
    return nil
}

Client side:

var conn = new WebSocket("ws://localhost:8080/api/messages/websocket");

conn.onclose = function (e) {
    console.log("onclose fired");
};

conn.onopen = function (e) {
    console.log("onopen fired");
};

conn.onmessage = function (e) {
    console.log(e.data);
};              

setTimeout(function () {
    conn.send("foo!");
}, 1500);

When I load the page first time, only foo! is outputted to the console. So all in all, after loading the page once, and then reloading it twice I get an output like this:

2015/09/18 19:04:39 foo!
2015/09/18 19:04:41 websocket: close 1001
2015/09/18 19:04:41 http: response.Write on hijacked connection
2015/09/18 19:04:43 foo!
2015/09/18 19:04:44 websocket: close 1001
2015/09/18 19:04:44 http: response.Write on hijacked connection
2015/09/18 19:04:46 foo!

What does this mean? I'm I doing something wrong?

  • 写回答

1条回答 默认 最新

报告相同问题?

悬赏问题

  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败