-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsession.go
74 lines (62 loc) · 1.45 KB
/
session.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
package sago
import (
"fmt"
"code.google.com/p/go.net/websocket"
)
type message struct {
Id string `json:"id"`
Action string `json:"action"`
Args *map[string]interface{} `json:"args"`
}
type Session struct {
ws *websocket.Conn
Data map[string]interface{}
}
var live_sessions = map[*Session]bool{}
func addLiveSession(s *Session) {
live_sessions[s] = true
}
func removeLiveSession(s *Session) {
delete(live_sessions, s)
}
func (s Session) Start() {
fmt.Println("Connected:", s.ws)
addLiveSession(&s)
s.listen()
removeLiveSession(&s)
fmt.Println("Disconnected:", s.ws)
}
func (s Session) listen() {
for {
var msg message
err := websocket.JSON.Receive(s.ws, &msg)
if err != nil {
fmt.Println(err)
break
}
fmt.Printf("Session: %i, Message: %i\n", s, msg)
handle(&s, msg)
}
}
func (s Session) Send(response_id string, name string, args map[string]interface{}) error {
msg := message { Id: response_id, Action: name, Args: &args }
return websocket.JSON.Send(s.ws, msg)
}
func SendAll(name string, args map[string]interface{}) {
SendAllExcept(name, args, make([]*Session, 0))
}
func SendAllExcept(name string, args map[string]interface{}, exceptions []*Session) {
var excepted bool
for k := range live_sessions {
excepted = false
for _, v := range exceptions {
if v == k {
excepted = true
break
}
}
if !excepted {
k.Send("", name, args)
}
}
}