client.rb 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. require 'net/http'
  2. require 'json'
  3. require 'thread'
  4. pubsub_URL = 'http://pubsub.example.org:2069/'
  5. def do_stuff_with(event)
  6. print("Got a pubsub event!:\n")
  7. print(event, "\n")
  8. end
  9. def listen(url)
  10. ps_thread = Thread.new do
  11. begin
  12. uri = URI.parse(url)
  13. Net::HTTP.start(uri.host, uri.port, :use_ssl => url.match(/^https:/) ? true : false) do |http|
  14. request = Net::HTTP::Get.new uri.request_uri
  15. http.request request do |response|
  16. body = ''
  17. response.read_body do |chunk|
  18. body += chunk
  19. if chunk.end_with? "\n"
  20. event = JSON.parse(body.chomp)
  21. body = ''
  22. if event['stillalive'] # pingback
  23. print("ping? PONG!\n")
  24. else
  25. do_stuff_with(event)
  26. end
  27. end
  28. end
  29. end
  30. end
  31. rescue Errno::ECONNREFUSED => e
  32. restartable = true
  33. STDERR.puts e
  34. sleep 3
  35. rescue Exception => e
  36. STDERR.puts e
  37. STDERR.puts e.backtrace
  38. end
  39. end
  40. return ps_thread
  41. end
  42. begin
  43. ps_thread = listen(pubsub_URL)
  44. print("Pubsub thread started, waiting for results...\n")
  45. while ps_thread.alive?
  46. sleep 10
  47. end
  48. end