package hook
import (
"fmt"
"log"
"net/http"
"sync"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
)
var webSocketMap sync.Map
func Web(c *gin.Context) {
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
log.Println("升级协议", r.Header["User-Agent"])
return true
},
}
//var clients = make(map[string]*websocket.Conn)
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Println(err)
return
}
defer conn.Close()
userId := c.Query("uid")
toId := c.Query("toid")
// clients[userId] = conn
webSocketMap.Store(userId, conn) //添加用户到暂存区
//log.Println("用户id:", userId, clients, len(clients))
for {
mt, message, err := conn.ReadMessage()
log.Println("获取客户端发送的消息:" + string(message))
fmt.Println(mt)
if err != nil {
log.Println(err)
break
}
if Ws, ok := webSocketMap.Load(toId); ok {
fmt.Println("数据1")
Ws.(*websocket.Conn).WriteMessage(websocket.TextMessage, []byte(message))
} else {
fmt.Println("数据2")
err2 := conn.WriteMessage(websocket.TextMessage, []byte(message))
if err2 != nil {
log.Println("write:", err2)
break
}
}
//var msg = "春风得意马蹄疾,一日看尽长安花"
// toid, ok := clients[toId]
// fmt.Println("666", clients)
// if ok {
// fmt.Println("数据1")
// toid.WriteMessage(mt, []byte(fmt.Sprintf("[%s] %s", userId, message)))
// } else {
// fmt.Println("数据2")
// err2 := conn.WriteMessage(websocket.TextMessage, []byte(message))
// if err2 != nil {
// log.Println("write:", err2)
// break
// }
// }
}
}
03-12
491