Class: Bridge::Tcp

Inherits:
EventMachine::Connection
  • Object
show all
Defined in:
lib/tcp.rb

Overview

:nodoc: all

Instance Method Summary collapse

Constructor Details

#initialize(connection) ⇒ Tcp

Returns a new instance of Tcp.



6
7
8
9
10
11
12
13
# File 'lib/tcp.rb', line 6

def initialize connection
  @buffer = ''
  @len = 0
  @pos = 0
  @callback = nil
  @connection = connection
  start
end

Instance Method Details

#post_initObject



15
16
17
# File 'lib/tcp.rb', line 15

def post_init
  @connection.onopen self
end

#read(len, &cb) ⇒ Object



31
32
33
34
35
36
# File 'lib/tcp.rb', line 31

def read len, &cb
  @buffer = ''
  @len = len
  @pos = 0
  @callback = cb
end

#receive_data(data) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/tcp.rb', line 19

def receive_data data
  left = @len - @pos
  if data.length >= left
    @buffer << data.slice(0, left)
    @callback.call @buffer
    receive_data data.slice(left..-1) unless data.nil?
  else
    @buffer << data
    @pos = @pos + data.length
  end
end

#send(arg) ⇒ Object



51
52
53
54
# File 'lib/tcp.rb', line 51

def send arg
  # Prepend length header to message
  send_data([arg.length].pack("N") + arg)
end

#startObject



38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/tcp.rb', line 38

def start
  # Read header bytes
  read 4 do |data|
    # Read body bytes
    read data.unpack('N')[0] do |data|
      # Call message handler
      @connection.onmessage({:data => data}, self)
      # Await next message
      start
    end
  end
end

#unbindObject



56
57
58
# File 'lib/tcp.rb', line 56

def unbind
  @connection.onclose
end