N
N
Nube2018-04-06 10:50:47
JavaScript
Nube, 2018-04-06 10:50:47

Why is the webscoket connection being closed?

Page A establishes a webscoket connection. Now, when I go to page B, which also establishes a webscoket connection, my server crashes with a websocket: close 1001 (going away) error .
In the console in the browser it gives "failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED"
js code

var socket = new WebSocket("ws://localhost:8080/ws" );
socket.onmessage = function (event) {
    DownloadScene(event)
}
socket.onclose =function (err){
    console.log(err)
}
socket.onerror = function(error) {
    console.log('WebSocket Error: ' + error);
}
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 also use the code above on page B. How can I make it reconnect?
Top handler:
func WebSocketConnect(w http.ResponseWriter,r *http.Request)  {
  conn,err := upGrader.Upgrade(w, r, nil)
  //defer conn.Close()
  if err != nil {
    log.Println("here")
    log.Println(err)

  }

    webSocketHandler(conn)

}
func webSocketHandler(conn *websocket.Conn) {

  println("new connect")
  err := conn.ReadJSON(&query)
  if err != nil {
    log.Fatal(err)
    return
  }
  switch query.QueryType {
  case model.LoadSceneQuery :
    err := json.Unmarshal(query.Data,&frame)
    if err!= nil{
      log.Fatal(err)
    }
    LoadFrame(frame.Temp,conn,nil)
  case model.LoadFrameQuery:
    break
  }
}

It seems to me that a script is needed that would start the connection again, but in js I can not (.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nube, 2018-04-07
@Nube

The solution turned out to be simple), you need to replace log.Fatal(err) with log.Println(err) or something else. Every time the page is reloaded, the websocket connection is closed, so websocket: close 1001 (going away). this is the norm).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question