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, readErr := r.Read(buffer) for _, conn := range conns { conn.SetDeadline(time.Now().Add(writeTimeout)) _, writeErr := conn.Write(buffer[:i]) if writeErr != nil { return writeErr } } if readErr != nil { if errors.Is(readErr, io.EOF) { break } else { return readErr } } } return nil }