-
Notifications
You must be signed in to change notification settings - Fork 0
/
Connection.go
72 lines (61 loc) · 1.45 KB
/
Connection.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
package Coral
import (
"encoding/json"
"github.com/google/uuid"
"github.com/gorilla/websocket"
"sync"
)
type Conn struct {
*websocket.Conn
ID uuid.UUID
locker sync.Mutex
actions map[string]func(content interface{}) error
channels map[string]*Channel
}
func newConn(conn *websocket.Conn) *Conn {
return &Conn{
Conn: conn,
ID: uuid.New(),
actions: map[string]func(content interface{}) error{},
channels: map[string]*Channel{},
locker: sync.Mutex{},
}
}
func (c *Conn) Close() {
_ = c.Conn.Close()
globalChannel.RemoveMember(c.ID.String())
onConnectionCloseAction(c)
}
func (c *Conn) On(t string, callback func(content interface{}) error) {
c.actions[t] = callback
}
func (c *Conn) Emit(t string, content interface{}) error {
barray, err := json.Marshal(message{ID: c.ID.String(), Type: t, Content: content})
if err != nil {
return err
}
c.locker.Lock()
defer c.locker.Unlock()
if err := c.WriteMessage(websocket.TextMessage, barray); err != nil {
return err
}
return nil
}
func (c *Conn) Broadcast(t string, content interface{}) {
for id, conn := range globalChannel.GetMembers() {
if c.ID.String() != id {
go conn.Emit(t, content)
}
}
}
func (c *Conn) GetChannels() {
}
func (c *Conn) BroadcastToChannel(name string, t string, content interface{}) {
if channel, ok := channels[name]; ok {
for id, conn := range channel.connections {
if c.ID.String() != id {
go conn.Emit(t, content)
}
}
}
}