Reputation: 13
When the client reloads the page, the server issues an error - websocket: close 1001 (going away). When the client reloads the page, does not the websocket connection reconnect? I recently started studying programming, so please forgive if the question is stupid. Client code
var socket = new WebSocket("ws://localhost:8080/ws" );
socket.onmessage = function (event) {
DownloadScene(event)
}
function DownloadScene(event) {
var data = JSON.parse(event.data)
document.getElementById(data.id).innerHTML = data.body;
}
function loadScene(scene) {
var page = {
query_type:"loadScene",
data : {temp:scene}
}
var event = JSON.stringify(page);
socket.send(event);
}
I'm using the gorilla websocket library to build a connection.
Server code
func WebSocketHandler(w http.ResponseWriter, r *http.Request) {
conn, err := upGrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
for { webSocketHandler(conn)}
defer conn.Close()
}
func webSocketHandler(conn *websocket.Conn) {
println("new connect")
err := conn.ReadJSON(&query)
if err != nil {
log.Fatal(err)
return
}
switch query.QueryType {
case "loadScene" :
err := json.Unmarshal(query.Data,&frames)
if err!= nil{
log.Fatal(err)
}
var buf bytes.Buffer
data := frame.ExecuteTemplate(&buf,"frame",nil)
if data!=nil{
log.Fatal(data)
}
res,e := json.Marshal(&Frame{"scene",buf.String()})
if e !=nil{
log.Println(e)
}
errs := conn.WriteMessage(1,res)
if err!=nil{
log.Fatal(errs)
}
}
}
Upvotes: 1
Views: 1279
Reputation: 1387
If on page load websocket connects, then there are no worries. When page refreshes the client will connect to server. you can ignore the exception for websocket close 1001.
Upvotes: 0
Reputation: 3984
In go
, log.Fatal(..) exits your application.
err := conn.ReadJSON(&query)
will return an err
when the client connection closes and the next block:
if err != nil {
log.Fatal(err)
return
}
will close the go
server and the Javascript client will be unable to reconnect.
Your server structure also doesn't look quite correct - WebSocketHandler
is invoked to handle a single connection:
.
http.HandleFunc("/", WebSocketHandler)
log.Fatal(http.ListenAndServe("localhost:8080", nil))
}
func WebSocketHandler(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("Error upgrading websocket:", err)
return
}
defer conn.Close()
for {
err = conn.ReadJSON(&query)
if err != nil {
log.Print("Error reading query: ", err)
return
}
.
// -- process query here --
.
}
}
Upvotes: 2