diff --git a/ap/ap.go b/ap/ap.go index 5c9bb80b..11c44df6 100644 --- a/ap/ap.go +++ b/ap/ap.go @@ -80,12 +80,6 @@ func (ap *Accesspoint) init(ctx context.Context) (err error) { return fmt.Errorf("failed initializing diffiehellman: %w", err) } - // close previous connection if any - if ap.conn != nil { - _ = ap.conn.Close() - ap.conn = nil - } - // open connection to accesspoint attempts := 0 for { @@ -95,9 +89,13 @@ func (ap *Accesspoint) init(ctx context.Context) (err error) { conn, err := proxy.Dial(ctx_, "tcp", addr) cancel() if err == nil { + // close previous connection if any + if ap.conn != nil { + _ = ap.conn.Close() + } + // we assign to ap.conn after because if Dial fails we'll have a nil ap.conn which we don't want ap.conn = conn - // Successfully connected. ap.log.Debugf("connected to %s", addr) return nil } else if attempts >= 6 { diff --git a/dealer/dealer.go b/dealer/dealer.go index c10cad48..dc301f85 100644 --- a/dealer/dealer.go +++ b/dealer/dealer.go @@ -84,7 +84,8 @@ func (d *Dealer) connect(ctx context.Context) error { return fmt.Errorf("failed obtaining dealer access token: %w", err) } - if conn, _, err := websocket.Dial(ctx, fmt.Sprintf("wss://%s/?access_token=%s", d.addr(ctx), accessToken), &websocket.DialOptions{ + addr := d.addr(ctx) + if conn, _, err := websocket.Dial(ctx, fmt.Sprintf("wss://%s/?access_token=%s", addr, accessToken), &websocket.DialOptions{ HTTPClient: d.client, HTTPHeader: http.Header{ "User-Agent": []string{librespot.UserAgent()}, @@ -92,15 +93,18 @@ func (d *Dealer) connect(ctx context.Context) error { }); err != nil { return err } else { + if d.conn != nil { + _ = d.conn.Close(websocket.StatusServiceRestart, "") + } + // we assign to d.conn after because if Dial fails we'll have a nil d.conn which we don't want d.conn = conn + d.log.Debug(fmt.Sprintf("connected to %s", addr)) } // remove the read limit d.conn.SetReadLimit(math.MaxUint32) - d.log.Debugf("dealer connection opened") - return nil }