-
Notifications
You must be signed in to change notification settings - Fork 0
/
wsocket.go
101 lines (88 loc) · 2.24 KB
/
wsocket.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
package main
import (
"fmt"
"net/http"
"sync"
"time"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { return true },
}
type WSMessage struct {
RoomID string `json:"room_id"`
Time time.Time `json:"time"`
From string `json:"from"`
Message string `json:"message"`
UserID string `json:"user_id"`
Email string `json:"email"`
}
type WSHandler struct {
TTL time.Duration
Stop chan struct{}
Conn *websocket.Conn
Memory *sync.RWMutex
Messagechan chan WSMessage
}
func (wsh *WSHandler) Write(rooms map[string]*Room) {
var lastMessage time.Time
var ticker = time.NewTicker(wsh.TTL)
fmt.Println("WSHandler.Write: new writer")
defer wsh.Conn.Close()
defer fmt.Println("WSHandler.Write: closing connection")
dasWriter:
for {
select {
case <-ticker.C:
if time.Since(lastMessage) > wsh.TTL {
fmt.Println("WSHandler.Write: closing connection due to inactivity")
break dasWriter
}
case message := <-wsh.Messagechan:
lastMessage = time.Now()
// fmt.Printf("got message %+v", message)
room, ok := rooms[message.RoomID]
if !ok {
fmt.Println("WSHandler.Write: room not found", message.RoomID)
continue
}
room.AddMessage(message)
room.Memory.RLock()
out := room.GetMesssages()
for conn := range room.Connections {
err := conn.WriteMessage(websocket.TextMessage, []byte(out))
if err != nil {
fmt.Println("WSHandler.Write: error writing message", err)
conn.Close()
delete(room.Connections, conn)
}
}
room.Memory.RUnlock()
case <-wsh.Stop:
break dasWriter
}
}
}
func (wsh *WSHandler) ServeWS(rooms map[string]*Room, w http.ResponseWriter, r *http.Request) {
parts := r.URL.Path
roomID := parts[len("/ws/"):]
if roomID == "" {
http.Error(w, "room id not found", http.StatusBadRequest)
return
}
room, ok := rooms[roomID]
if !ok {
http.Error(w, "room id not found", http.StatusBadRequest)
return
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
http.Error(w, "error upgrading connection", http.StatusInternalServerError)
return
}
wsh.Conn = conn
room.AddConnection(wsh)
go wsh.Write(rooms)
}