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?