views:

19

answers:

0

I'm working on creating a background script that uses EventMachine to connect to a server with WebSockets. The script will be run using DelayedJob or Resque. I've been able to get it to talk to the WebSockets server and send messages, but whenever an error is raised within the EventMachine loop it doesn't crash the script - which is what should happen (and what I need to have happen). I don't have to use EventMachine as I'm only sending WebSocket messages and not receiving them - but I'd love any help on this :) thank you!

#!/usr/bin/env ruby
require 'rubygems'
require 'eventmachine'
require 'em-http'

class Job
  include EventMachine::Deferrable

  def self.perform
    job = Job.new
    EventMachine.run {
      http = EventMachine::HttpRequest.new("ws://localhost:8080/").get :timeout => 0

      http.errback { puts "oops" }
      http.callback {
        puts "WebSocket connected!"
        http.send("Hello watcher")
      }

      http.stream { |msg| }
      job.callback { puts "done" }
      Thread.new { 
        job.execute(http)
        http.close
        EventMachine.stop
      }
    }
  end

  def execute(h)
      sleep 1
      puts "Job Runner!"
      h.send("welcome!")
      sleep 2
      asdsadsa # here I am trying to simulate an error
      sleep 1
      h.send("we are all done!")
      sleep 1
      set_deferred_status :succeeded
  end
end

Job.perform