-
Notifications
You must be signed in to change notification settings - Fork 1
/
nusan.go
106 lines (89 loc) · 2.07 KB
/
nusan.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
package main
import (
"fmt"
"log"
"net/http"
"sync"
"time"
"github.com/gorilla/websocket"
)
type NusanLauncher struct {
ch *chan string
wsConn *websocket.Conn
wsMutex sync.Mutex
}
func NusanLauncherConnect(port int) (*NusanLauncher, error) {
log.Printf("-> Starting socket for NUSAN LAUNCHER on port: %d", port)
webServer := &http.Server{
Addr: fmt.Sprintf(":%d", port),
ReadHeaderTimeout: 3 * time.Second,
}
ch := make(chan string)
nl := NusanLauncher{
ch: &ch,
}
http.HandleFunc("/bytejammer", wsNusan(nl))
// #TODO: This is a bit iffy - nl may be available before the connection can be used
go func() {
if err := webServer.ListenAndServe(); err != nil {
log.Fatal(err)
}
}()
return &nl, nil
}
func wsNusan(nl NusanLauncher) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
var err error
nl.wsConn, err = wsUpgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("ERR upgrade:", err)
return
}
// #TODO: Not great!
defer nl.wsConn.Close()
go nl.nusanWsOperatorRead()
go nl.nusanWsOperatorWrite()
// #TODO: handle exit
for {
}
}
}
// #TODO: Is this used?
func (nl *NusanLauncher) nusanWsOperatorRead() {
for {
/*
var msg interface{}
err := nl.conn.ReadJSON(&msg)
if err != nil {
log.Fatal(err)
}
fmt.Printf("-> NUSAN LAUNCHER: %v\n", msg)
*/
}
}
type NusanLauncherMsg struct {
Data struct {
RoomName string `json:"RoomName"`
NickName string `json:"NickName"`
} `json:"Data"`
}
func (nl *NusanLauncher) nusanWsOperatorWrite() {
for {
select {
case msg := <-(*nl.ch):
fmt.Printf("-> NUSAN TOSEND: %v\n", msg)
nlMsg := NusanLauncherMsg{}
nlMsg.Data.RoomName = "bytejammer"
nlMsg.Data.NickName = msg
err := nl.sendData(&nlMsg)
if err != nil {
log.Fatal(err)
}
}
}
}
func (nl *NusanLauncher) sendData(data interface{}) error {
nl.wsMutex.Lock()
defer nl.wsMutex.Unlock()
return nl.wsConn.WriteJSON(data)
}