Last active
November 1, 2018 17:45
-
-
Save kenichi/a3a5cfa0bfa90b51971837067f0e2254 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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