File: em.rb

package info (click to toggle)
ruby-eye 0.7-5.1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 672 kB
  • sloc: ruby: 5,003; makefile: 3
file content (57 lines) | stat: -rw-r--r-- 1,155 bytes parent folder | download | duplicates (2)
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
require 'bundler/setup'
require 'eventmachine'

def answer(data)
  case data
    when 'ping' then "pong\n"
    when 'bad' then "what\n"
    when 'timeout' then sleep 5; "ok\n"
    when 'exception' then raise 'haha'
    when 'quit' then EM.stop
    when 'big' then 'a' * 10_000_000
  end
end

class Echo < EM::Connection
  def post_init
    puts "-- someone connected to the echo server!"
  end

  def receive_data data
    puts "receive #{data.inspect} "
    send_data(answer(data))
  end

  def unbind
     puts "-- someone disconnected from the echo server!"
  end
end

class EchoObj < EM::Connection
  include EM::P::ObjectProtocol

  def post_init
    puts "-- someone connected to the echo server!"
  end

  def receive_object obj # {:command => 'ping'}
    puts "receive #{obj.inspect}"
    send_object(answer(obj[:command]).chop)
  end

  def unbind
    puts "-- someone disconnected from the echo server!"
  end
end

trap "QUIT" do
  puts "quit signal, stopping"
  EM.stop
end

EM.run do
  EM.start_server '127.0.0.1', 33221, Echo
  EM.start_server '127.0.0.1', 33222, EchoObj
  EM.start_server "/tmp/em_test_sock", nil, Echo
  puts 'started'
end