correct closing of the websocket connection by the server

Viewed 297

The TryCloseNormally function closes the websocket connection from the server side. There are two versions of this function. The first one just sends a closing request. And the second one is waiting for a response-a copy from the client. Which of these functions is correct?

version 1

func TryCloseNormally(wsConn *websocket.Conn) error {
    closeNormalClosure := websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")
    if err := wsConn.WriteControl(websocket.CloseMessage, closeNormalClosure, time.Now().Add(time.Second)); err != nil {
        return err
    }
    return wsConn.Close()
}

version 2

// The function tries to close the connection according to the RFC 6455 standard.
// The function ALWAYS closes the connection.
//
// To handle the case where the peer sent a data message before the sending the close message,
// function read and discard data messages until an Normalclose is returned.
func TryCloseNormally(wsConn *websocket.Conn, closeCode int, textErr string) error {
    defer wsConn.Close()
    closeNormalClosure := websocket.FormatCloseMessage(closeCode, textErr)
    if err := wsConn.WriteControl(websocket.CloseMessage, closeNormalClosure, time.Now().Add(time.Second)); err != nil {
        return err
    }
    if err := wsConn.SetReadDeadline(time.Now().Add(time.Second)); err != nil {
        return err
    }
    for {
        _, _, err := wsConn.ReadMessage()
        if websocket.IsCloseError(err, closeCode) {
            return nil
        }
        if err != nil {
            return err
        }
    }
}

Do I need to wait for a response from the client? Or it doesn't affect anything.

1 Answers

Both are correct.

The second function implements the closing handshake. The handshake makes it possible for the server to read all messages sent by the client.

Use the first function if it’s OK to discard messages sent by the client.

Related