我想向客户端发送密码,但总是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 dev工具控制台中,粘贴如下
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);};
这都是因为“睡眠”
//time.Sleep(10*time.Second)
conn.Close()
删除睡眠后,代码工作正常。