1.下载github.com/gorilla/websocket
执行
go get github.com/gorilla/websocket
- 服务端
package main
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/websocket"
)
var (
upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
// 允许所有客户端连接
return true
},
}
)
func wsHandler(w http.ResponseWriter, r *http.Request) {
// 升级HTTP连接为WebSocket连接
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Fatal("Upgrade: ", err)
return
}
defer conn.Close()
for {
// 读取客户端发送的消息
messageType, p, err := conn.ReadMessage()
if err != nil {
log.Println("ReadMessage: ", err)
break
}
fmt.Printf("Received message: %s\n", p)
// 向客户端发送数据
err = conn.WriteMessage(messageType, p)
if err != nil {
log.Println("WriteMessage: ", err)
break
}
}
}
func main() {
http.HandleFunc("/ws", wsHandler)//ws加上请求的时候就是 ws:/127.0.0.1:8080/ws 可以变成/
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("连接失败: ", err)
}
}
浏览器客户端
var face_socket_new = 'ws://localhost:8080/ws';
var ws = new WebSocket(face_socket_new);
ws.onopen = () => {
console.log('listenCheckTicket websocket connect success!');
let data = {
data: 'ok',
};
ws.send(JSON.stringify(data)); //将消息发送到服务端
};
ws.onmessage = (e) => {
var data = JSON.parse(e.data);
console.log('data:', data.msg);
dialog.toast(data.msg, 'none', 3000, () => {
ws.close();
window.location.reload();
});
};
ws.onclose = (e) => {
console.log('close',e);
};
ws.onerror = (e) => {
console.log(e);
};