123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114 |
- package Server
- import (
- "App_Warn/lib"
- "App_Warn/logs"
- "fmt"
- "github.com/gin-gonic/gin"
- "github.com/gorilla/websocket"
- "net/http"
- "time"
- )
- var upGrader = websocket.Upgrader{
- ReadBufferSize: 1024,
- WriteBufferSize: 1024,
- HandshakeTimeout: 10 * time.Second,
- CheckOrigin: func(r *http.Request) bool {
- return true
- },
- }
- func WsHandle(c *gin.Context) {
- //升级get请求为webSocket协议
- ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
- if err != nil {
- c.Writer.Write([]byte(err.Error()))
- return
- }
- defer func() {
- ClearSubscription(ws) // 清楚订阅
- ws.Close()
- }()
- uuid, _ := c.GetQuery("uuid")
- logs.Println("ws上线:", fmt.Sprintf("%p", ws), "uuid:", uuid)
- // 追加 订阅UUID
- SubConn := []*websocket.Conn{}
- // 从map中读取数据
- val, ok := lib.SubClinets.Load(uuid)
- if ok {
- SubConn = val.([]*websocket.Conn)
- }
- SubConn = append(SubConn, ws)
- // 写入map
- lib.SubClinets.Store(uuid, SubConn)
- for {
- //读取ws中的数据
- _, _, err := ws.ReadMessage()
- if err != nil {
- c.Writer.Write([]byte(err.Error()))
- break
- }
- //fmt.Println("client message " + string(message) +"|"+ string(mt))
- //fmt.Println(mt)
- ////time.Sleep(time.Second * 10)
- //写入ws数据
- err = ws.WriteMessage(1, []byte(time.Now().String()))
- if err != nil {
- ClearSubscription(ws) // 清楚订阅
- ws.Close()
- break
- }
- //fmt.Println("system message " + time.Now().String())
- }
- }
- // 发送 数据
- func WebsocketWriteJSON(client *websocket.Conn, msg interface{}) error {
- err := client.WriteJSON(msg)
- if err != nil {
- ClearSubscription(client) // 清楚订阅
- client.Close()
- }
- return nil
- }
- func App_Warn_Sand(Uuid string, msg interface{}) string {
- val, ok := lib.SubClinets.Load(Uuid)
- if ok {
- SubConn := val.([]*websocket.Conn)
- for _, v := range SubConn {
- WebsocketWriteJSON(v, msg)
- }
- } else {
- return "发送无手机在线!"
- }
- return "发送成功!"
- }
- // 清楚订阅
- func ClearSubscription(client *websocket.Conn) {
- logs.Println("清楚订阅:", fmt.Sprintf("%p", client))
- // 编列所有订阅号
- lib.SubClinets.Range(func(key, value interface{}) bool {
- ConnList := value.([]*websocket.Conn)
- Sn := key.(string)
- logs.Println("SubClinets_数量|", Sn, len(ConnList))
- for i, v := range ConnList {
- if v == client {
- logs.Println("删除订阅:", fmt.Sprintf("%p", v), Sn)
- ConnList = append(ConnList[:i], ConnList[i+1:]...)
- lib.SubClinets.Store(Sn, ConnList)
- break
- }
- }
- return true
- })
- }
|