websocket 写关闭消息总是发送 1006
websocket Write Close Message always send 1006
我想给客户端发送关闭码,但总是1006
我试过了,
func ServeWs(w http.ResponseWriter, r *http.Request) {
conn := Upgrade(w, r)
msg := websocket.FormatCloseMessage(4001, "myError")
// case 1
conn.WriteMessage(websocket.CloseMessage, msg)
// case 2
//conn.WriteControl(websocket.CloseMessage, msg, time.Now().Add(time.Second))
// case 3
//w, err := conn.NextWriter(websocket.CloseMessage)
//if err != nil {
// return
//}
//if _, err = w.Write(msg); err != nil {
// log.Println(err)
//}
//w.Close()
time.Sleep(10*time.Second)
conn.Close()
}
func Upgrade(w http.ResponseWriter, r *http.Request) *websocket.Conn{
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return nil
}
return conn
}
但并非所有这些情况都有效。我怎样才能将 1006 以外的内容发送给客户端?
我还测试了 Node js ws 包来验证客户端的。
const WebSocket = require('ws');
const ws = new WebSocket.Server({ port: 8088 });
ws.on('connection', function connection(ws) {
ws.close(1000, 'bac');
});
这个 javascript 代码工作正常。
===已添加===
用于测试的客户端代码。在 chrome 开发工具控制台中,粘贴到下方
conn = new WebSocket("ws://127.0.0.1:8088/connect"); conn.onclose = function(evt){console.log("do", evt);}; conn.onerror = function(err){console.log("err", err);}; conn.onmessage = function(msg){console.log("msg", msg);};
这都是因为 "Sleep"
//time.Sleep(10*time.Second)
conn.Close()
删除睡眠后,代码工作正常。
我想给客户端发送关闭码,但总是1006
我试过了,
func ServeWs(w http.ResponseWriter, r *http.Request) {
conn := Upgrade(w, r)
msg := websocket.FormatCloseMessage(4001, "myError")
// case 1
conn.WriteMessage(websocket.CloseMessage, msg)
// case 2
//conn.WriteControl(websocket.CloseMessage, msg, time.Now().Add(time.Second))
// case 3
//w, err := conn.NextWriter(websocket.CloseMessage)
//if err != nil {
// return
//}
//if _, err = w.Write(msg); err != nil {
// log.Println(err)
//}
//w.Close()
time.Sleep(10*time.Second)
conn.Close()
}
func Upgrade(w http.ResponseWriter, r *http.Request) *websocket.Conn{
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return nil
}
return conn
}
但并非所有这些情况都有效。我怎样才能将 1006 以外的内容发送给客户端?
我还测试了 Node js ws 包来验证客户端的。
const WebSocket = require('ws');
const ws = new WebSocket.Server({ port: 8088 });
ws.on('connection', function connection(ws) {
ws.close(1000, 'bac');
});
这个 javascript 代码工作正常。
===已添加===
用于测试的客户端代码。在 chrome 开发工具控制台中,粘贴到下方
conn = new WebSocket("ws://127.0.0.1:8088/connect"); conn.onclose = function(evt){console.log("do", evt);}; conn.onerror = function(err){console.log("err", err);}; conn.onmessage = function(msg){console.log("msg", msg);};
这都是因为 "Sleep"
//time.Sleep(10*time.Second)
conn.Close()
删除睡眠后,代码工作正常。