-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
205 lines (178 loc) · 4.38 KB
/
main.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
package main
import (
"log"
"net/http"
"regexp"
"time"
"github.com/gorilla/websocket"
)
type errorCode string
func (e errorCode) String() string {
return string(e)
}
type bsError struct {
code errorCode
expr string
}
func (e *bsError) Error() string {
return "error: " + e.code.String() + ": `" + e.expr + "`"
}
const (
errWrongPath errorCode = "Wrong path"
)
const (
// Time allowed to write a message to the peer.
writeWait = 10 * time.Second
// Time allowed to read the next pong message from the peer.
pongWait = 60 * time.Second
// Send pings to peer with this period. Must be less than pongWait.
pingPeriod = (pongWait * 9) / 10
// Maximum message size allowed from peer.
maxMessageSize = 64 * 1024
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { return true },
}
type client struct {
referee *referee
room string
nick string
conn *websocket.Conn
send chan []byte
}
type message struct {
room string
nick string
msg []byte
}
func (c *client) readFromConnectionPump() {
defer func() {
c.referee.unregister <- c
c.conn.Close()
}()
c.conn.SetReadLimit(maxMessageSize)
c.conn.SetReadDeadline(time.Now().Add(pongWait))
c.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })
for {
_, msg, err := c.conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
log.Printf("error: %v", err)
}
break
}
if c.nick != "" {
c.referee.broadcast <- message{room: c.room, nick: c.nick, msg: msg}
}
}
}
func (c *client) writeToConnectionPump() {
ticker := time.NewTicker(pingPeriod)
defer func() {
ticker.Stop()
c.conn.Close()
}()
for {
select {
case message, ok := <-c.send:
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
if !ok {
// The referee closed the channel.
c.conn.WriteMessage(websocket.CloseMessage, []byte{})
return
}
w, err := c.conn.NextWriter(websocket.TextMessage)
if err != nil {
return
}
w.Write(message)
if err := w.Close(); err != nil {
return
}
case <-ticker.C:
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
return
}
}
}
}
type referee struct {
register chan *client
unregister chan *client
clients map[*client]bool
broadcast chan message
}
func newReferee() *referee {
return &referee{
register: make(chan *client),
unregister: make(chan *client),
clients: make(map[*client]bool),
broadcast: make(chan message),
}
}
func (r *referee) run() {
for {
select {
case client := <-r.register:
log.Printf("+++client: %p\n", client)
r.clients[client] = true
case client := <-r.unregister:
if _, ok := r.clients[client]; ok {
log.Printf("---client: %p\n", client)
delete(r.clients, client)
close(client.send)
}
case message := <-r.broadcast:
for client := range r.clients {
if client.room == message.room && (client.nick == message.nick || client.nick == "") {
select {
case client.send <- message.msg:
default:
close(client.send)
delete(r.clients, client)
}
}
}
}
}
}
func getRoomAndNick(url string) (*string, *string, error) {
re, err := regexp.Compile(`^/([A-Za-z0-9_]{3,64})/([A-Za-z0-9_]{0,16})$`)
if err != nil {
return nil, nil, err
}
match := re.FindStringSubmatch(url)
if len(match) < 2 {
return nil, nil, &bsError{code: errWrongPath, expr: "Wrong room name and/or nickname."}
}
return &match[1], &match[2], nil
}
func main() {
log.Println("Launching Bonzomatic server.")
referee := newReferee()
go referee.run()
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
room, nick, err := getRoomAndNick(r.URL.Path)
if err != nil {
log.Println(err)
return
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
log.Println("Client connected to room: '" + *room + "' with nick: '" + *nick + "'")
client := &client{referee: referee, room: *room, nick: *nick, conn: conn, send: make(chan []byte, 256)}
client.referee.register <- client
go client.writeToConnectionPump()
go client.readFromConnectionPump()
})
err := http.ListenAndServe(":9000", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}