Class: UState::Server::Connection

Inherits:
EventMachine::Connection
  • Object
show all
Defined in:
lib/ustate/server/connection.rb

Overview

Instantiated by EventMachine for each new connection Mostly from Thin.

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#backendObject

Returns the value of attribute backend.



4
5
6
# File 'lib/ustate/server/connection.rb', line 4

def backend
  @backend
end

#indexObject

Returns the value of attribute index.



5
6
7
# File 'lib/ustate/server/connection.rb', line 5

def index
  @index
end

Instance Method Details

#post_initObject

Called to prepare the connection for a request



8
9
10
11
# File 'lib/ustate/server/connection.rb', line 8

def post_init
  @state = :length
  @buffer = ""
end

#receive_data(data = '') ⇒ Object

Called when data is received



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/ustate/server/connection.rb', line 14

def receive_data(data = '')
  @buffer << data
 
  case @state
  when :length
    # Length header
    if @buffer.bytesize >= 4
      @length = @buffer.slice!(0,4).unpack('N').first
      @state = :data
      receive_data unless @buffer.empty?
    end
  when :data
    # Data
    if @buffer.bytesize >= @length
      receive_message @buffer.slice!(0, @length)
      @state = :length
      receive_data unless @buffer.empty?
    end
  end
end

#receive_message(data) ⇒ Object

Called with a message type and data.



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/ustate/server/connection.rb', line 36

def receive_message(data)
  begin
    message = UState::Message.decode data
    if states = message.states
      # State update
      states.each do |state|
        @index << state
      end
      send UState::Message.new(ok: true)
    elsif q = message.query
      res = @index.query(q)
      send UState::Message.new(ok: true, states: res)
    else
      send UState::Message.new(ok: false, error: "unknown message type")
    end
  rescue Exception => e
    puts e
    puts e.backtrace.join("\n")
    m = UState::Message.new(ok: false, error: e.message)
    send m
  end
end

#remote_addressObject



69
70
71
# File 'lib/ustate/server/connection.rb', line 69

def remote_address
  socket_address
end

#send(message) ⇒ Object



59
60
61
# File 'lib/ustate/server/connection.rb', line 59

def send(message)
  send_data message.encode_with_length
end

#terminate_requestObject



73
74
75
# File 'lib/ustate/server/connection.rb', line 73

def terminate_request
  close_connection_after_writing rescue nil
end

#unbindObject

Called when the connection is unbound from the socket and can no longer be used to process requests.



65
66
67
# File 'lib/ustate/server/connection.rb', line 65

def unbind
  @backend.connection_finished self
end