Friday, January 28, 2011

EventMachine echo server

Edit: I am trying to find the public interface for event servers and connections.


We need the require 'rubygems' so that the interpreter will know to search the rubygems install paths. Apparently, module locations are not hard coded into the interpreter.
#!/usr/bin/env ruby                                                              
require 'rubygems'
require 'eventmachine'

port = ARGV[0].to_i
puts "PORT>>>#{port}<<<"

module Echo
  def receive_data(data)
    puts "RECV>>>#{data.chomp}<<<"
    send_data(data)
    puts "SEND>>>#{data.chomp}<<<"
    if data.downcase.chomp == 'quit'
      EM.next_tick { EM.stop }
    end
  end
end

EM.run do
  EM.start_server("0.0.0.0", port, Echo)
end

Single line socket puts

#!/usr/bin/env ruby
require 'socket'

send_msg = ARGV[1]
send_msg ||= "[nil msg]"
puts "MSG  >>>#{send_msg}<<<"
port = ARGV[0].to_i
puts "PORT >>>#{port}<<<"

TCPSocket.open("localhost", port) do |sk|
  sk.puts send_msg
  puts "SENT >>>#{send_msg}<<<"

  recv_msg = sk.gets
  puts "RECV >>>#{recv_msg.chomp}<<<"
end

Echo Socket (single thread, single connection)

#!/usr/bin/env ruby
require 'socket'
port = (ARGV[0] || 7777).to_i

TCPServer.open('localhost', port) do |svr|
  loop do #do-while loop
    sk = svr.accept

    input = sk.gets
    puts "RECV >>>#{input.chomp}<<<"
    sk.puts input
    puts "SENT >>>#{input.chomp}<<<"
    sk.close
    break if input.downcase.chomp == 'quit'
  end #end do-while loop
end

Documentation

I had to learn everything from the web. Bulky books are a problem for me.

Almost to low level API docs
http://www.ruby-doc.org/core-1.8.7/

Good "Programming Ruby" book
http://www.ruby-doc.org/docs/ProgrammingRuby/

EventMachine


Very Intro PDF
http://everburning.com/wp-content/uploads/2009/02/eventmachine_presentation.pdf

Better Intro PDF
http://everburning.com/wp-content/uploads/2009/02/eventmachine_introduction_10.pdf

Very Basic Tutorial
http://20bits.com/articles/an-eventmachine-tutorial/

Low Level API
http://eventmachine.rubyforge.org/