ruby sample

Ruby code posted
created at 08 Feb 19:48, updated at 13 Feb 15:40

Edit | Back
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
require 'rubygems'
require 'em-http'

def subscribe(opts)
  listener = EventMachine::HttpRequest.new('http://cm1.subg.ru/listen?cid='+ opts[:channel]).get :head => opts[:head]
  listener.callback { 
    puts "Listener recieved: " + listener.response + "\n"
    
    modified = listener.response_header['LAST_MODIFIED']
    subscribe({:channel => opts[:channel], :head => {'If-Modified-Since' => modified}})
  }
end

EventMachine.run {
  channel = "pub"
  
  EM.add_periodic_timer(5) do
    time = Time.now
    publisher = EventMachine::HttpRequest.new('http://cm1.subg.ru/publish?id='+channel).post :body => "Hello @ #{time}"
    publisher.callback {
      puts "Published message @ #{time}"
      puts "Response code: " + publisher.response_header.status.to_s
      puts "Headers: " + publisher.response_header.inspect
      puts "Body: \n" + publisher.response
      puts "\n"
    }
  end

  subscribe(:channel => channel)
  subscribe(:channel => channel)
}

993 Bytes in 3 ms with coderay