I've written a simple application that captures frames from my webcam and streams the frames via a websocket.
The stream implementation I've come up with feels weird. Networking is not my strong suit. I am wondering if the communication between the server and app can be written better.
type Stream struct {
Frame []byte
}
func (s *Stream) ServeHTTP(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Fatal(err)
}
//This feels weird
//I use a ticker that ticks with the fps of the camera
//to send the individual frames to the browser
ticker := time.NewTicker(time.Millisecond * 33)
for _ = range ticker.C {
if err = conn.WriteMessage(websocket.TextMessage, s.Frame); err != nil {
log.Fatal(err)
}
}
}
s := server.Stream{}
wg := sync.WaitGroup{}
wg.Add(2)
go func() {
http.Handle("/", &server.TemplateHandler{Filename: "index.html"})
http.Handle("/ws", &s)
http.ListenAndServe(":8080", nil)
}()
go func() {
err = camera.StartStreaming()
checkErr(err)
for {
frame, err := camera.ReadFrame()
checkErr(err)
//Also weird, but hey it works
s.Frame = []byte(base64.StdEncoding.EncodeToString(frame))
}
}()
wg.Wait()