Class: SSE::SSEClient

Inherits:
Object
  • Object
show all
Defined in:
lib/sse_client/sse_client.rb

Overview

A lightweight Server-Sent Events implementation, relying on two gems: socketry for sockets with read timeouts, and http_tools for HTTP response parsing. The overall logic is based on [github.com/Tonkpils/celluloid-eventsource].

Constant Summary collapse

DEFAULT_CONNECT_TIMEOUT =
10
DEFAULT_READ_TIMEOUT =
300
DEFAULT_RECONNECT_TIME =
1
MAX_RECONNECT_TIME =
30

Instance Method Summary collapse

Constructor Details

#initialize(uri, options = {}) {|_self| ... } ⇒ SSEClient

Returns a new instance of SSEClient.

Yields:

  • (_self)

Yield Parameters:



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/sse_client/sse_client.rb', line 18

def initialize(uri, options = {})
  @uri = URI(uri)
  @stopped = Concurrent::AtomicBoolean.new(false)

  @headers = options[:headers] ? options[:headers].clone : {}
  @connect_timeout = options[:connect_timeout] || DEFAULT_CONNECT_TIMEOUT
  @read_timeout = options[:read_timeout] || DEFAULT_READ_TIMEOUT
  @logger = options[:logger] || default_logger

  if options[:proxy]
    @proxy = options[:proxy]
  else
    proxyUri = @uri.find_proxy
    if !proxyUri.nil? && (proxyUri.scheme == 'http' || proxyUri.scheme == 'https')
      @proxy = proxyUri
    end
  end

  reconnect_time = options[:reconnect_time] || DEFAULT_RECONNECT_TIME
  @backoff = Backoff.new(reconnect_time, MAX_RECONNECT_TIME)

  @on = { event: ->(_) {}, error: ->(_) {} }
  @last_id = nil

  yield self if block_given?

  Thread.new do
    run_stream
  end
end

Instance Method Details

#closeObject



61
62
63
64
65
66
# File 'lib/sse_client/sse_client.rb', line 61

def close
  if @stopped.make_true
    @cxn.close if !@cxn.nil?
    @cxn = nil
  end
end

#on(event_name, &action) ⇒ Object



49
50
51
# File 'lib/sse_client/sse_client.rb', line 49

def on(event_name, &action)
  @on[event_name.to_sym] = action
end

#on_error(&action) ⇒ Object



57
58
59
# File 'lib/sse_client/sse_client.rb', line 57

def on_error(&action)
  @on[:error] = action
end

#on_event(&action) ⇒ Object



53
54
55
# File 'lib/sse_client/sse_client.rb', line 53

def on_event(&action)
  @on[:event] = action
end