-
-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathmain.go
336 lines (280 loc) · 6.92 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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
package main
import (
"bufio"
"bytes"
"context"
"fmt"
"log"
"net/http"
"os"
"strings"
"sync"
"time"
"github.com/kataras/neffos"
"github.com/kataras/neffos/gobwas"
"github.com/kataras/neffos/gorilla"
)
const (
endpoint = "localhost:9090"
namespace = "default"
timeout = 20 * time.Second
)
type Users struct {
mu sync.RWMutex
entries map[string]*userConn // key = user's unique identifier, i.e "username".
}
// returns true if new conn.
func (u *Users) conn(c *neffos.NSConn) (*userConn, bool) {
user := c.Conn.ID()
u.mu.RLock()
entry, ok := u.entries[user]
u.mu.RUnlock()
if !ok {
entry = &userConn{
conns: make(map[*neffos.NSConn]struct{}),
}
u.mu.Lock()
u.entries[user] = entry
u.mu.Unlock()
}
entry.addConn(c)
return entry, !ok
}
func (u *Users) get(c *neffos.NSConn) *userConn {
u.mu.RLock()
entry, ok := u.entries[c.Conn.ID()]
u.mu.RUnlock()
if !ok {
return nil
}
return entry
}
func (u *Users) remove(user string) {
u.mu.Lock()
delete(u.entries, user)
u.mu.Unlock()
}
type userConn struct {
mu sync.RWMutex
conns map[*neffos.NSConn]struct{}
}
// returns true for new conn.
func (u *userConn) addConn(c *neffos.NSConn) bool {
u.mu.RLock()
_, ok := u.conns[c]
u.mu.RUnlock()
if !ok {
u.mu.Lock()
u.conns[c] = struct{}{}
u.mu.Unlock()
return true
}
return false
}
func (u *userConn) deleteConn(c *neffos.NSConn) (wasLast bool) {
u.mu.Lock()
delete(u.conns, c)
wasLast = len(u.conns) == 0
u.mu.Unlock()
return
}
func (u *userConn) Emit(event string, data []byte) (ok bool) {
u.mu.RLock()
defer u.mu.RUnlock()
for c := range u.conns {
ok = c.Emit(event, data)
if !ok {
delete(u.conns, c)
}
}
return
}
func (u *userConn) Disconnect(ctx context.Context) {
u.mu.RLock()
defer u.mu.RUnlock()
for c := range u.conns {
c.Disconnect(ctx)
}
}
func (u *userConn) Close() {
u.mu.Lock()
defer u.mu.Unlock()
for c := range u.conns {
c.Conn.Close()
delete(u.conns, c)
}
}
var users = &Users{
entries: make(map[string]*userConn),
}
var handler = neffos.WithTimeout{
ReadTimeout: timeout,
WriteTimeout: timeout,
Namespaces: neffos.Namespaces{
"default": neffos.Events{
neffos.OnNamespaceConnected: func(c *neffos.NSConn, msg neffos.Message) error {
_, isNew := users.conn(c)
if isNew || c.Conn.IsClient() {
log.Printf("[%s] connected to [%s].", c.Conn.ID(), msg.Namespace)
}
if !c.Conn.IsClient() {
c.Emit("chat", []byte("welcome to server's namespace"))
}
return nil
},
neffos.OnNamespaceDisconnect: func(c *neffos.NSConn, msg neffos.Message) error {
if msg.Err != nil {
log.Printf("This client can't disconnect yet, server does not allow that action, reason: %v", msg.Err)
return nil
}
conn := users.get(c)
if conn == nil {
return nil
}
wasLast := conn.deleteConn(c)
if wasLast {
users.remove(c.Conn.ID())
log.Printf("[%s] disconnected from [%s].", c.Conn.ID(), msg.Namespace)
}
if c.Conn.IsClient() {
os.Exit(0)
}
return nil
},
"chat": func(c *neffos.NSConn, msg neffos.Message) error {
if !c.Conn.IsClient() {
// this is possible too:
// if bytes.Equal(msg.Body, []byte("force disconnect")) {
// println("force disconnect")
// return c.Disconnect()
// }
log.Printf("--server-side-- send back the message [%s:%s]", msg.Event, string(msg.Body))
// c.Emit(msg.Event, msg.Body)
// c.Server().Broadcast(nil, msg) // to all including this connection.
// c.Server().Broadcast(c, msg) // to all except this connection.
users.get(c).Emit(msg.Event, msg.Body)
}
log.Printf("---------------------\n[%s] %s", c.Conn.ID(), msg.Body)
return nil
},
},
},
}
func main() {
args := os.Args[1:]
if len(args) == 0 {
log.Fatalf("expected program to start with 'server' or 'client' argument")
}
side := args[0]
var (
upgrader = gobwas.DefaultUpgrader
dialer = gobwas.DefaultDialer
)
if len(args) > 1 {
method := args[1]
if method == "gorilla" {
upgrader = gorilla.DefaultUpgrader
dialer = gorilla.DefaultDialer
if side == "server" {
log.Printf("Using with Gorilla Upgrader.")
} else {
log.Printf("Using with Gorilla Dialer.")
}
}
}
switch side {
case "server":
server(upgrader)
case "client":
client(dialer)
default:
log.Fatalf("unexpected argument, expected 'server' or 'client' but got '%s'", side)
}
}
func server(upgrader neffos.Upgrader) {
srv := neffos.New(upgrader, handler)
srv.IDGenerator = func(w http.ResponseWriter, r *http.Request) string {
return r.RemoteAddr[:strings.IndexByte(r.RemoteAddr, ':')]
}
srv.OnConnect = func(c *neffos.Conn) error {
log.Printf("[%s] connected to server.", c.ID())
// time.Sleep(3 * time.Second)
// c.Connect(nil, namespace) // auto-connect to a specific namespace.
// c.Write(namespace, "chat", []byte("Welcome to the server (after namespace connect)"))
// println("client connected")
return nil
}
srv.OnDisconnect = func(c *neffos.Conn) {
log.Printf("[%s] disconnected from the server.", c.ID())
}
srv.OnUpgradeError = func(err error) {
log.Printf("ERROR: %v", err)
}
log.Printf("Listening on: %s\nPress CTRL/CMD+C to interrupt.", endpoint)
go http.ListenAndServe(endpoint, srv)
fmt.Fprint(os.Stdout, ">> ")
scanner := bufio.NewScanner(os.Stdin)
for {
if !scanner.Scan() {
log.Printf("ERROR: %v", scanner.Err())
return
}
text := scanner.Bytes()
if bytes.Equal(text, []byte("force disconnect")) {
// for _, conn := range srv.GetConnectionsByNamespace(namespace) {
// conn.Disconnect()
// }
// srv.Broadcast(nil, neffos.Message{
// Namespace: namespace,
// Event: neffos.OnNamespaceDisconnect,
// })
srv.Do(func(c *neffos.Conn) {
// c.Close()
c.Namespace(namespace).Disconnect(nil)
}, false)
} else {
// srv.Do(func(c *neffos.Conn) {
// c.Write(namespace, "chat", text)
// }, false)
srv.Broadcast(nil, neffos.Message{Namespace: namespace, Event: "chat", Body: text})
}
fmt.Fprint(os.Stdout, ">> ")
}
}
func client(dialer neffos.Dialer) {
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(timeout))
defer cancel()
client, err := neffos.Dial(ctx, dialer, endpoint, handler)
if err != nil {
panic(err)
}
defer client.Close()
// connectNamespaceTimeout, cancel2 := context.WithTimeout(context.Background(), timeout/2)
// defer cancel2()
// c, err := client.WaitServerConnect(nil, namespace)
c, err := client.Connect(nil, namespace)
if err != nil {
panic(err)
}
// println("connected.")
fmt.Fprint(os.Stdout, ">> ")
scanner := bufio.NewScanner(os.Stdin)
for {
if !scanner.Scan() {
log.Printf("ERROR: %v", scanner.Err())
return
}
text := scanner.Bytes()
if bytes.Equal(text, []byte("exit")) {
if err := c.Disconnect(nil); err != nil {
// log.Printf("from server: %v", err)
}
continue
}
ok := c.Emit("chat", text)
if !ok {
break
}
fmt.Fprint(os.Stdout, ">> ")
}
}