From 6b7da29eea100b92659a3f1f5df6958ebad544c8 Mon Sep 17 00:00:00 2001 From: xegineering Date: Wed, 27 Nov 2024 21:29:39 +0100 Subject: Introduce io.Reader-based streamContext() This prepares the switch to adding more sources than web URLs. Everything providing an io.Reader can then simply use this internal function in the background to avoid code duplication. --- soundbox/streaming.go | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 soundbox/streaming.go (limited to 'soundbox/streaming.go') diff --git a/soundbox/streaming.go b/soundbox/streaming.go new file mode 100644 index 0000000..5852dcf --- /dev/null +++ b/soundbox/streaming.go @@ -0,0 +1,50 @@ +package soundbox + +import ( + "context" + "errors" + "io" + "net" + "time" +) + +const bufferSize = 20 + +const writeTimeout = 1 * time.Second + +func streamContext(ctx context.Context, r io.Reader, targets []net.HardwareAddr) error { + conns := make([]net.Conn, 0) + for _, target := range targets { + conn, err := dialContext(ctx, target) + if err != nil { + return err + } + conns = append(conns, conn) + } + defer func() { + for _, conn := range conns { + conn.Close() + } + }() + + for { + buffer := make([]byte, bufferSize) + i, err := r.Read(buffer) + if err != nil { + if errors.Is(err, io.EOF) { + break + } else { + return err + } + } + for _, conn := range conns { + conn.SetDeadline(time.Now().Add(writeTimeout)) + _, err = conn.Write(buffer[:i]) + if err != nil { + return err + } + } + } + + return nil +} -- cgit v1.2.3-70-g09d2