Class: Protoplasm::EMServer

Inherits:
EventMachine::Connection
  • Object
show all
Defined in:
lib/protoplasm/server/em_server.rb

Constant Summary collapse

CONTROL_REQUEST =
0

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#_typesObject

Returns the value of attribute _types.



23
24
25
# File 'lib/protoplasm/server/em_server.rb', line 23

def _types
  @_types
end

Class Method Details

.start(types, port) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/protoplasm/server/em_server.rb', line 7

def self.start(types, port)
  if EM.reactor_running?
    EM::start_server("0.0.0.0", port, self) do |srv|
      srv._types = types
      yield srv if block_given?
    end
  else
    begin
      EM.run do
        start(types, port)
      end
    rescue Interrupt
    end
  end
end

Instance Method Details

#data_readyObject



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/protoplasm/server/em_server.rb', line 39

def data_ready
  @control = @data.slice!(0, 1).unpack("C").first unless @control
  case @control
  when CONTROL_REQUEST
    @size = @data.slice!(0, 8).unpack("Q").first unless @size

    if @data.size >= @size
      buf = @data.slice!(0, @size)
      @size, @control = nil, nil
      obj = _types.request_class.decode(buf)
      type = _types.request_type_for_request(obj)
      @_response_types << type unless type.void?
      EM.next_tick { send(:"process_#{type.field}", obj.send(type.field)) }
      data_ready unless @data.empty?
      #EM.next_tick { data_ready } #todo left over data needs to be processed still
    end
  else
    # illegal char
    close_connection
  end
end

#finish_streamingObject



35
36
37
# File 'lib/protoplasm/server/em_server.rb', line 35

def finish_streaming
  close_connection_after_writing
end

#post_initObject



25
26
27
28
# File 'lib/protoplasm/server/em_server.rb', line 25

def post_init
  @_response_types = []
  @data = ''
end

#receive_data(data) ⇒ Object



30
31
32
33
# File 'lib/protoplasm/server/em_server.rb', line 30

def receive_data(data)
  @data << data
  data_ready
end

#send_response(*args) ⇒ Object



61
62
63
64
65
66
67
68
69
# File 'lib/protoplasm/server/em_server.rb', line 61

def send_response(*args)
  type = @_response_types.first
  @_response_types.shift unless type.streaming?
  obj = type.response_class.new(*args)
  s = ''
  obj.encode(s)
  send_data [s.size].pack("Q")
  send_data s
end