Ws.go
885 Bytes
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
package Api
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
uuid "github.com/satori/go.uuid"
"letu/Lib/Ws"
)
var wsupgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func WsPage(c *gin.Context) {
conn, err := wsupgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
fmt.Println("Failed to set websocket upgrade: %+v", err)
return
}
// websocket connect
_uuid, _ := uuid.NewV4()
client := &Ws.Client{
_uuid.String(),
conn,
}
Ws.Manager.Register <- client
for {
_, msg, err := conn.ReadMessage()
if err != nil {
println(err.Error())
Ws.Manager.Unregister <- client
client.Socket.Close()
break
}
sMsg := string(msg)
println("收到消息:", sMsg)
switch sMsg {
case "test":
client.Send([]byte("hahaha"))
case "test2":
client.Send([]byte("hahaha2"))
}
}
}