diff --git a/README.md b/README.md index 414b385..317dd6c 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,15 @@ # EventSource client for EventMachine -source = EM::EventSource.new ("/live/meeting", {:start => 0}) + source = EM::EventSource.new ("/live/meeting", {:start => 0}) -source.message do |message| -end + source.message do |message| + end -source.error do |error| -end + source.error do |error| + end -source.on "plop" do |message| -end + source.on "plop" do |message| + end -source.start -source.close + source.start + source.close diff --git a/em-eventsource.gemspec b/em-eventsource.gemspec new file mode 100644 index 0000000..0feca39 --- /dev/null +++ b/em-eventsource.gemspec @@ -0,0 +1,19 @@ +Gem::Specification.new do |s| + s.name = "em-eventsource" + s.version = "0.0.1" + s.date = Time.now.utc.strftime("%Y-%m-%d") + s.homepage = "http://github.com/af83/em-eventsource" + s.authors = "François de Metz" + s.email = "francois.de.metz@af83.com" + s.description = "" + s.summary = "" + s.extra_rdoc_files = %w(README.md) + s.files = Dir["LICENSE", "README.md", "Gemfile", "lib/**/*.rb"] + s.require_paths = ["lib"] + s.rubygems_version = %q{1.3.7} + s.add_dependency "eventmachine", "1.0.0.beta3" + s.add_dependency "em-http-request", "1.0.0.beta4" + s.add_development_dependency "minitest", "~>2.0" + s.add_development_dependency "bundler" + s.add_development_dependency "rake" +end diff --git a/lib/em-eventsource.rb b/lib/em-eventsource.rb index 1f0c1a1..951f163 100644 --- a/lib/em-eventsource.rb +++ b/lib/em-eventsource.rb @@ -1,31 +1,50 @@ +require "eventmachine" +require "em-http-request" + module EventMachine class EventSource def initialize(url, query={}, headers={}) - @Url = url + @url = url @query = query @headers = headers @closed = false @lastid = nil @retry = 3 # seconds + + @errors = [] + @messages = [] + @on = {} end def on(type, &block) - + @on[type] << block end def message(&block) - + @messages << block end def error(&block) + @errors << block + end + # Start subscription + def start + @closed = false + listen + end + + # Cancel subscription + def close + @closed = true + @req.close end + protected + def listen - @req = prepare_request(:get, @url, - { :query => @query, - :head => {'Last-Event-Id' => @lastid }.merge(@headers)}) + @req = prepare_request @req.errback do next if @canceled EM.add_timer(@retry) do @@ -54,16 +73,10 @@ def listen end end - # Start subscription - def start - @closed = false - listen - end - - # Cancel subscription - def close - @closed = true - @req.close + def prepare_request + conn = EM::HttpRequest.new(@url) + conn.get({ :query => @query, + :head => {'Last-Event-Id' => @lastid }.merge(@headers)}) end end end