sse icon indicating copy to clipboard operation
sse copied to clipboard

Feature Request: Let's implement a client.AutoReconnect() method on lost connections.

Open Muddz opened this issue 5 years ago • 5 comments

I think it would be a great addition to the library if we could implement an auto reconnecting feature for the Client.go

Right now the Client will actually keep trying to connect with the amount of attempts decided by the backoff.Retry() method, but only IF the Client has been started with an unreachable stream (server) from start and then it will stop when it has established a connection with the stream

But the Client will not try again in the same way if it loses the connection from a stream it already was connected to, because the readLoop() method will detect this condition err == io.EOF and return nill to the erChan and thereby killing of the backoff.Retry()

An very simple idea to a solution for this would be something like this:

var AutoReconnect = false //[NEW] default should be false
func (c *Client) readLoop(reader *EventStreamReader, outCh chan *Event, erChan chan error) {
for {
	// Read each new line and process the type of event
	event, err := reader.ReadEvent()
	if err != nil {
		if err == io.EOF {
			if !autoReconnect {   //[NEW]  Check if user has enabled autoReconnect
				erChan <- nil
				return
			}
		}

		// run user specified disconnect function
		if c.disconnectcb != nil {
			c.disconnectcb(c)
		}
		erChan <- err
		return
	}

	// If we get an error, ignore it.
	if msg, err := c.processEvent(event); err == nil {
		if len(msg.ID) > 0 {
			c.EventID = string(msg.ID)
		} else {
			msg.ID = []byte(c.EventID)
		}
		// Send downstream
		outCh <- msg
	}
  }
}

This works and I have tried it on a Live-server.

Muddz avatar Mar 13 '20 17:03 Muddz

I faced with that issue as well.

quarckster avatar May 03 '20 08:05 quarckster

@quarckster I solved this by implementing the suggested code above and it works perfectly

Muddz avatar May 03 '20 21:05 Muddz

+1

koolay avatar Oct 14 '22 10:10 koolay

code: https://github.com/r3labs/sse/pull/145

yi-ge avatar Jan 21 '23 06:01 yi-ge

Interesting, I just noticed this after writing #147 and #148

I don't understand why the EOF special case is there by default (especially as the backoff will end silently without any error).

pjcdawkins avatar Feb 07 '23 22:02 pjcdawkins