This repository has been archived by the owner on Jul 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
websocket_server.go
80 lines (68 loc) · 1.82 KB
/
websocket_server.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
package nadeshiko
import (
"encoding/json"
"golang.org/x/net/websocket"
"io"
"log"
"strconv"
)
//TODO this function is too long needs clean up
func websocketServer(handler func(*Document)) func(*websocket.Conn) {
return func(connection *websocket.Conn) {
log.Printf("New client connection\n")
document := Document{websocket: connection}
handler(&document)
for {
var buf string
//TODO Consider using JSON codec for websocket
err := websocket.Message.Receive(connection, &buf)
if err != nil {
if err == io.EOF {
log.Println("Websocket client disconnected")
} else {
log.Printf("ERROR reading from socket: %v \n", err)
}
break
}
if verbose {
quotedContet := strconv.Quote(buf)
log.Printf("received: %s\n", quotedContet)
}
var jsonArray []string
json.Unmarshal([]byte(buf), &jsonArray)
//TODO check length of jsonArray
if callbackStruct, ok := callbacks[jsonArray[0]]; ok {
//TODO danger, huge possibility for data races
go func() {
callbackStruct.callback(jsonArray...)
if callbackStruct.oneTime {
if verbose {
log.Printf("Removing one-time callback \n")
}
deleteCallback(jsonArray[0])
}
if verbose {
log.Printf("Current callbacks count %d \n", len(callbacks))
}
}()
} else {
log.Printf("Can't find callback for %s \n", jsonArray[0])
}
}
document.ClientDisconnected = true
for callbackID, callbackStruct := range callbacks {
if callbackStruct.connection == nil {
log.Fatalln("This should not happen")
}
if callbackStruct.connection == connection {
if verbose {
log.Printf("Removing callback %s for disconnected client\n", callbackID)
}
deleteCallback(callbackID)
}
}
if verbose {
log.Printf("Current callbacks count %d \n", len(callbacks))
}
}
}