该TryCloseNormally函数从服务器端关闭 websocket 连接。该函数有两个版本。第一个仅发送关闭请求。第二个正在等待响应——来自客户端的副本。这些函数中哪个是正确的?
版本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()
}
Run Code Online (Sandbox Code Playgroud)
版本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
}
}
}
Run Code Online (Sandbox Code Playgroud)
我需要等待客户的回复吗?或者说不影响什么。
| 归档时间: |
|
| 查看次数: |
1720 次 |
| 最近记录: |