forked from SimonWaldherr/GoRealtimeWeb
/
realtimeweb.go
217 lines (196 loc) · 5.27 KB
/
realtimeweb.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
package main
import (
"encoding/json"
"fmt"
"golang.org/x/net/websocket"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"runtime"
"strconv"
"strings"
"syscall"
"time"
)
type Connections struct {
clients map[chan string]bool
addClient chan chan string
removeClient chan chan string
messages chan string
}
var hub = &Connections{
clients: make(map[chan string]bool),
addClient: make(chan (chan string)),
removeClient: make(chan (chan string)),
messages: make(chan string),
}
func (hub *Connections) Init() {
go func() {
for {
select {
case s := <-hub.addClient:
hub.clients[s] = true
log.Println("Added new client")
case s := <-hub.removeClient:
delete(hub.clients, s)
log.Println("Removed client")
case msg := <-hub.messages:
for s, _ := range hub.clients {
s <- msg
}
log.Printf("Broadcast \"%v\" to %d clients", msg, len(hub.clients))
}
}
}()
}
func httpHandler(w http.ResponseWriter, r *http.Request) {
f, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Streaming not supported!", http.StatusInternalServerError)
return
}
if r.URL.Path == "/send" {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Println(err)
}
str := string(body)
hub.messages <- str
f.Flush()
return
}
messageChannel := make(chan string)
hub.addClient <- messageChannel
notify := w.(http.CloseNotifier).CloseNotify()
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
for i := 0; i < 1440; {
select {
case msg := <-messageChannel:
jsonData, _ := json.Marshal(msg)
str := string(jsonData)
if r.URL.Path == "/events/sse" {
fmt.Fprintf(w, "data: {\"str\": %s, \"time\": \"%v\"}\n\n", str, time.Now())
} else if r.URL.Path == "/events/lp" {
fmt.Fprintf(w, "{\"str\": %s, \"time\": \"%v\"}", str, time.Now())
}
f.Flush()
case <-time.After(time.Second * 60):
if r.URL.Path == "/events/sse" {
fmt.Fprintf(w, "data: {\"str\": \"No Data\"}\n\n")
} else if r.URL.Path == "/events/lp" {
fmt.Fprintf(w, "{\"str\": \"No Data\"}")
}
f.Flush()
i++
case <-notify:
f.Flush()
i = 1440
hub.removeClient <- messageChannel
}
}
}
func websocketHandler(ws *websocket.Conn) {
var in string
messageChannel := make(chan string)
hub.addClient <- messageChannel
for i := 0; i < 1440; {
select {
case msg := <-messageChannel:
jsonData, _ := json.Marshal(msg)
str := string(jsonData)
in = fmt.Sprintf("{\"str\": %s, \"time\": \"%v\"}\n\n", str, time.Now())
if err := websocket.Message.Send(ws, in); err != nil {
hub.removeClient <- messageChannel
i = 1440
}
case <-time.After(time.Second * 60):
in = fmt.Sprintf("{\"str\": \"No Data\"}\n\n")
if err := websocket.Message.Send(ws, in); err != nil {
hub.removeClient <- messageChannel
i = 1440
}
}
i++
}
}
func telnetHandler(c *net.TCPConn) {
defer c.Close()
fmt.Printf("Connection from %s to %s established.\n", c.RemoteAddr(), c.LocalAddr())
io.WriteString(c, fmt.Sprintf("Welcome on %s\n", c.LocalAddr()))
buf := make([]byte, 4096)
for {
n, err := c.Read(buf)
if (err != nil) || (n == 0) {
c.Close()
break
}
str := strings.TrimSpace(string(buf[0:n]))
hub.messages <- str
io.WriteString(c, "sent to "+strconv.Itoa(len(hub.clients))+" clients\n")
}
time.Sleep(150 * time.Millisecond)
fmt.Printf("Connection from %v closed.\n", c.RemoteAddr())
c.Close()
return
}
func listenForTelnet(ln *net.TCPListener) {
for {
conn, err := ln.AcceptTCP()
if err != nil {
fmt.Println(err)
continue
}
go telnetHandler(conn)
}
}
func main() {
fmt.Printf("application started at: %s\n", time.Now().Format(time.RFC822))
var starttime int64 = time.Now().Unix()
runtime.GOMAXPROCS(8)
hub.Init()
http.HandleFunc("/send", httpHandler)
http.HandleFunc("/events/sse", httpHandler)
http.HandleFunc("/events/lp", httpHandler)
http.Handle("/events/ws", websocket.Handler(websocketHandler))
http.Handle("/", http.FileServer(http.Dir("./")))
go http.ListenAndServe(":8000", nil)
ln, err := net.ListenTCP("tcp", &net.TCPAddr{
Port: 8001,
})
if err != nil {
fmt.Println(err)
os.Exit(1)
}
go listenForTelnet(ln)
var input string
for input != "exit" {
_, _ = fmt.Scanf("%v", &input)
if input != "exit" {
switch input {
case "", "0", "5", "help", "info":
fmt.Print("you can type \n1: \"exit\" to kill this application")
fmt.Print("\n2: \"clients\" to show the amount of connected clients")
fmt.Print("\n3: \"system\" to show info about the server")
fmt.Print("\n4: \"time\" to show since when this application is running")
fmt.Print("\n5: \"help\" to show this information")
fmt.Println()
case "1", "exit", "kill":
fmt.Println("application get killed in 5 seconds")
input = "exit"
time.Sleep(5 * time.Second)
case "2", "clients":
fmt.Printf("connected to %d clients\n", len(hub.clients))
case "3", "system":
fmt.Printf("CPU cores: %d\nGo calls: %d\nGo routines: %d\nGo version: %v\nProcess ID: %v\n", runtime.NumCPU(), runtime.NumCgoCall(), runtime.NumGoroutine(), runtime.Version(), syscall.Getpid())
case "4", "time":
fmt.Printf("application running since %d minutes\n", (time.Now().Unix()-starttime)/60)
}
}
}
os.Exit(0)
}