Skip to content

Instantly share code, notes, and snippets.

@pdswan
Created October 20, 2012 18:56
Show Gist options
  • Save pdswan/3924335 to your computer and use it in GitHub Desktop.
Save pdswan/3924335 to your computer and use it in GitHub Desktop.
Ruby event source without event machine
  1. Run the server

    % thin -R server.ru start
    
  2. Run the client

    % ruby threaded_clients.rb
    
source "http://rubygems.org"
gem 'thin'
gem 'cramp'
gem 'rack'
require 'cramp'
class Pump < Cramp::Action
self.transport = :sse
periodic_timer :pump, :every => 1
def pump
begin
render "#{times} times"
rescue TooManyTimesError
finish
end
end
class TooManyTimesError < StandardError; end
def times
@times = 0 unless defined?(@times)
@times += 1
raise TooManyTimesError unless @times <= 10
@times
end
end
run Pump
require 'socket'
class HttpRequest
def initialize(host, port=80)
@host = host
@port = port
@socket = TCPSocket.new host, port
@callbacks = { }
end
def start
socket.puts "GET / HTTP/1.1\r\n"
socket.puts "User-Agent: ruby\r\n"
socket.puts "Host: #{host}:#{port}\r\n"
socket.puts "Accept: */*\r\n"
socket.puts "\r\n"
read
end
def close
socket.close
end
def on(event, &block)
@callbacks[event] = block
end
def callback(event, *args)
find_callback(event).call(*args)
end
private
def find_callback(event)
@callbacks.fetch(event)
end
def read
# blocking IO causes threads
# to switch, hooray!
while data = socket.gets
callback(:data, data)
end
callback(:end)
close
end
attr_reader :host, :port, :socket, :block
end
threads = [ ]
10.times do |i|
threads << Thread.new do
request = HttpRequest.new('localhost', 3000) do |data|
puts "Request #{i} >> #{data}"
end
request.on(:data) do |data|
puts "Request #{i} >> #{data}"
end
request.on(:end) do
puts "Request #{i} >> END"
end
request.start
end
end
threads.map(&:join)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment