This repository has been archived by the owner on Dec 22, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ws.go
116 lines (93 loc) · 2.01 KB
/
ws.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
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
package main
import (
"log"
"time"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
)
const (
pingPeriod = 60 * time.Second
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
type connection struct {
ws *websocket.Conn
// send chan []byte
user *User
room *Room
}
type hub struct {
rooms map[string]*connection
}
var h = hub{
rooms: make(map[string]*connection),
}
func wshandler(context *gin.Context) {
w := context.Writer
r := context.Request
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("Failed to set websocket upgrade: %+v\n", err)
return
}
var room *Room
user := User{context.MustGet("key").(string)}
userRoom, err := getString("GET", "user:"+user.key)
// If user has a room save his connection
if err == nil {
room = &Room{userRoom, user}
log.Printf("User key: %s\n", user.key)
log.Printf("User room: %v\n", room)
}
c := &connection{
ws: conn,
// send: make(chan []byte),
user: &user,
room: room,
}
if err == nil {
// Save connection only when user has a room
h.rooms[room.name] = c
}
c.manage()
}
func (c *connection) manage() {
// ticker := time.NewTicker(pingPeriod)
log.Printf("INIT CONNECTION with USER=%v and ROOM=%v\n", c.user, c.room)
defer func() {
// Remove room and connection when host left
if c.room != nil {
delete(h.rooms, c.room.name)
exec("DEL", "user:"+c.user.key, "room:"+c.room.name)
log.Printf("Room removed")
}
// ticker.Stop()
c.ws.Close()
log.Printf("CLOSE CONNECTION\n")
}()
for {
// select {
// case <-ticker.C:
// c.ws.WriteMessage(websocket.PingMessage, []byte("ping:empty"))
// break
// default:
// Echo received message
t, msg, err := c.ws.ReadMessage()
if err != nil {
break
}
c.ws.WriteMessage(t, msg)
// }
}
}
func notifyHost(host string, msg string) {
log.Printf("Notify host\n")
c, ok := h.rooms[host]
if !ok {
log.Printf("No connection for host\n")
return
}
c.ws.WriteMessage(websocket.TextMessage, []byte(msg))
}