package main
import (
"encoding/json"
"fmt"
"net/http"
"github.com/gorilla/websocket"
)
var UP = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
var conns = map[string]*websocket.Conn{}
var readConnResult = map[string]string{}
func handler(w http.ResponseWriter, r *http.Request) {
conn, err := UP.Upgrade(w, r, nil)
// fmt.Printf("%+v\n", conn)
// f, err := conn.File()
// fmt.Println(f.Fd())
if err != nil {
fmt.Println(err)
return
}
for {
_, p, err := conn.ReadMessage()
if err != nil {
fmt.Println(err)
break
}
err = json.Unmarshal(p, &readConnResult)
if err != nil {
fmt.Println("JSON转换失败:", err)
return
}
conns[readConnResult["id"]] = conn
// fmt.Printf("%T\n", readConnResult)
// fmt.Println(readConnResult["msg"])
for tempConn := range conns {
if tempConn == readConnResult["id"] {
continue
}
conns[tempConn].WriteMessage(websocket.TextMessage, []byte(readConnResult["msg"]))
// fmt.Printf("%+v\n", conns[tempConn])
// fmt.Println(tempConn)
}
fmt.Println("\n", "conns的长度为:", len(conns))
}
defer conn.Close()
delete(conns, readConnResult["id"])
fmt.Println("服务关闭")
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}