require "rubygems"
require "eventmachine"
# From "An EventMachine Tutorial"
# http://20bits.com/articles/an-eventmachine-tutorial/
class Server < EventMachine::Connection
attr_accessor :status,:options
def receive_data
puts "#{@status} -- #{data}"
send_data("hello\n")
end
end
EventMachine::run do
# start_serverは3番目の引数に指定されたハンドラーを引数にyeildする
EM::start_server host,port,Server do |conn|
conn.options = {:my => 'options'}
conn.status = :OK
end
end
require "rubygems"
require "eventmachine"
# From "An EventMachine Tutorial"
# http://20bits.com/articles/an-eventmachine-tutorial/
module HttpHeaders
# connectionがセットアップされた直後に呼び出される。
# クライアントアプリならサーバーにつながった直後/サーバーアプリならクライアントが接続してきた直後
def post_init
send_data "GET /\r\n\r\n"
@data = ""
end
def receive_data(data)
@data << data
end
# クライアント/サーバー側のいずれかの接続が終了した時
# このhttp_clientの場合は、サーバーがデータを送り終えたら呼び出される
def unbind
puts "server have sent data"
if @data =~ /[\n][\r]*[\n]/m
$`.each do |line|
puts ">>> #{line}"
end
end
# ループを終了させる
EventMachine::stop_event_loop
end
end
EventMachine::run do
EventMachine::connect "google.com",80,HttpHeaders
end
require "rubygems"
require "eventmachine"
# Playing with EventMachine
# http://everburning.com/news/playing-with-eventmachine/
# EventMachineとEMは同じ
# runでイベントループが開始されるが、引数として渡されるブロックをその前に実行する
EventMachine::run do
# 定期的に実行されるタイマーを設定
EM.add_periodic_timer(1) { puts "Tick ..." }
# 指定した秒数が経過した後に、1回実行されるタイマーを設定
EM.add_timer(3) do
puts "I waited 3 seconds"
EM.stop_event_loop
end
end
puts "All done"