Skip to content

Instantly share code, notes, and snippets.

@kenichi
Last active November 1, 2018 17:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kenichi/a3a5cfa0bfa90b51971837067f0e2254 to your computer and use it in GitHub Desktop.
Save kenichi/a3a5cfa0bfa90b51971837067f0e2254 to your computer and use it in GitHub Desktop.
require 'net/http'
require 'set'
require 'uri'
uri = URI.parse 'https://example.com/events'
class ImageSet
def initialize
@set = Set.new
@mutex = Mutex.new
end
def << image_url
@mutex.synchronize { @set << image_url }
end
def fetch
@mutex.synchronize { @set.dup }
end
end
is = ImageSet.new
sse_thread = Thread.new do
Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
req = Net::HTTP::Get.new(uri)
req['accept'] = 'text/event-stream'
http.request(req) do |res|
res.read_body do |event|
event.split("\n").each do |l|
if l.start_with? 'data: '
image_url = l[6..-1]
is << image_url
end
end
end
end
end
end
loop do
sleep 5
p is.fetch.to_a
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment