1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
| package module
import ( "log" "net/http" "sync" "time"
"github.com/gin-gonic/gin" "github.com/gorilla/websocket" )
var (
news = make(map[string]chan interface{})
client = make(map[string]*websocket.Conn)
mux sync.Mutex )
func GetPushNews(context *gin.Context) { id := context.Query("userId") log.Println(id + "websocket链接")
WsHandler(context.Writer, context.Request, id) }
func DeleteClient(context *gin.Context) { id := context.Param("id")
conn, exist := getClient(id) if exist { conn.Close() deleteClient(id) } else { context.JSON(http.StatusOK, gin.H{ "mesg": "未找到该客户端", }) }
_, exist = getNewsChannel(id) if exist { deleteNewsChannel(id) } }
var wsupgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, HandshakeTimeout: 5 * time.Second,
CheckOrigin: func(r *http.Request) bool { return true }, }
func WsHandler(w http.ResponseWriter, r *http.Request, id string) { var conn *websocket.Conn var err error var exist bool
pingTicker := time.NewTicker(time.Second * 10) conn, err = wsupgrader.Upgrade(w, r, nil) if err != nil { log.Println(err) return }
addClient(id, conn)
m, exist := getNewsChannel(id) if !exist { m = make(chan interface{}) addNewsChannel(id, m) }
conn.SetCloseHandler(func(code int, text string) error { deleteClient(id) log.Println(code) return nil })
for { select { case content, _ := <-m:
err = conn.WriteJSON(content) if err != nil { log.Println(err) conn.Close() deleteClient(id) return } case <-pingTicker.C:
conn.SetWriteDeadline(time.Now().Add(time.Second * 20)) err = conn.WriteMessage(websocket.PingMessage, []byte{}) if err != nil { log.Println("send ping err:", err) conn.Close() deleteClient(id) return } } } }
func addClient(id string, conn *websocket.Conn) { mux.Lock() client[id] = conn mux.Unlock() }
func getClient(id string) (conn *websocket.Conn, exist bool) { mux.Lock() conn, exist = client[id] mux.Unlock() return }
func deleteClient(id string) { mux.Lock() delete(client, id) log.Println(id + "websocket退出") mux.Unlock() }
func addNewsChannel(id string, m chan interface{}) { mux.Lock() news[id] = m mux.Unlock() }
func getNewsChannel(id string) (m chan interface{}, exist bool) { mux.Lock() m, exist = news[id] mux.Unlock() return }
func deleteNewsChannel(id string) { mux.Lock() if m, ok := news[id]; ok { close(m) delete(news, id) } mux.Unlock() }
|