This repository has been archived by the owner on Oct 10, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
/
main.go
115 lines (95 loc) · 2.32 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
package main
import (
"code.google.com/p/go.net/websocket"
"flag"
"fmt"
"log"
"net/http"
"os"
"time"
)
var htdocsDir = flag.String("htdocs", ".", "htdocs directory")
func main() {
flag.Parse()
http.Handle("/ws/audio", websocket.Handler(handleWebsocket))
http.HandleFunc("/livestream", streamLiveData)
http.Handle("/", http.FileServer(http.Dir(*htdocsDir)))
log.Fatal(http.ListenAndServe(":8000", nil))
}
func handleWebsocket(s *websocket.Conn) {
log.Printf("Opened WebSocket")
startTime := time.Now()
f, err := os.OpenFile(fmt.Sprintf("%s/uploads/%s.mp3", *htdocsDir, time.Now().Format(time.RFC3339)), os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
log.Printf("os.OpenFile failed: %v", err)
return
}
defer f.Close()
sum := 0
count := 0
for {
data := make([]byte, 8192)
n, err := s.Read(data)
if err != nil {
log.Printf("s.Read failed: %v", err)
break
}
broadcastData(data[:n])
log.Printf("Received WebSocket frame: %d bytes", n)
count++
sum += n
if _, err := f.Write(data[:n]); err != nil {
log.Printf("f.Write failed: %v", err)
}
}
endBroadcast()
duration := time.Since(startTime)
log.Printf("Closed WebSocket, received %d frames (%d bytes), took %s (%.3f kb/s)", count, sum, duration, (float64(sum) / duration.Seconds()) / float64(1024))
}
func streamLiveData(w http.ResponseWriter, r *http.Request) {
ch := make(chan []byte)
registerClient(ch)
defer unregisterClient(ch)
f := w.(http.Flusher)
connClosed := w.(http.CloseNotifier).CloseNotify()
w.Header().Set("Content-Type", "audio/mpeg")
w.WriteHeader(http.StatusOK)
for {
select {
case data, ok := <-ch:
if !ok {
log.Printf("End of transmission.")
return
}
if _, err := w.Write(data); err != nil {
log.Printf("Writing data to client failed: %v", err)
return
}
f.Flush()
case <-connClosed:
log.Printf("Connection closed, stopping transmission.")
return
}
}
}
var clients = make(map[chan []byte]struct{})
func registerClient(ch chan []byte) {
clients[ch] = struct{}{}
log.Printf("Registered client %p", ch)
}
func unregisterClient(ch chan []byte) {
delete(clients, ch)
log.Printf("Unregistered client %p", ch)
}
func broadcastData(data []byte) {
for ch, _ := range clients {
select {
case ch <- data:
}
}
}
func endBroadcast() {
for ch, _ := range clients {
close(ch)
}
}