-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathws_server.go
66 lines (53 loc) · 1.2 KB
/
ws_server.go
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
package go_websocket
import (
"github.com/bwmarrin/snowflake"
"github.com/gorilla/websocket"
"net/http"
)
var (
snowflakeNode *snowflake.Node
wsUpgrader = &websocket.Upgrader{
ReadBufferSize: ReadBufferSize,
WriteBufferSize: WriteBufferSize,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
)
func init() {
ip, err := GetExternalIP()
if err != nil {
panic(err)
}
n := InetAtoN(ip)
snowflakeNode, err = snowflake.NewNode(n % 1023)
if err != nil {
panic(err)
}
}
func Upgrade(clientManage *ClientManage, w http.ResponseWriter, r *http.Request) (*Client, error) {
conn, err := wsUpgrader.Upgrade(w, r, nil)
if err != nil {
return nil, err
}
systemId := r.FormValue("system_id")
group := r.FormValue("group")
if systemId == "" {
systemId = RemoteIp(r)
}
//生成客户端ID
clientId := GenerateClientId()
//创建客户端
wsClient := NewClient(clientId, systemId, conn, clientManage)
if len(group) > 0 {
clientManage.AddGroupsByClient(wsClient, group)
}
//添加客户端
clientManage.Register(wsClient)
go wsClient.ReadLoop()
go wsClient.WriteLoop()
return wsClient, nil
}
func GenerateClientId() string {
return snowflakeNode.Generate().String()
}