Class: Bridge::Tcp

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

Overview

:nodoc: all

Instance Method Summary collapse

Methods included from SSLCertificateVerification

#ca_store, #ssl_handshake_completed, #ssl_verify_peer

Constructor Details

#initialize(connection) ⇒ Tcp

Returns a new instance of Tcp.



10
11
12
13
14
15
16
17
18
# File 'lib/tcp.rb', line 10

def initialize connection
  @buffer = ''
  @len = 0
  @pos = 0
  @callback = nil
  @connection = connection
  SSLCertificateVerification.ca_cert_file = File.expand_path('../../include/ssl/cacert.pem', __FILE__)
  start
end

Instance Method Details

#connection_completedObject



24
25
26
27
# File 'lib/tcp.rb', line 24

def connection_completed
  # connection now ready. call the callback
  @connection.onopen self
end

#post_initObject



20
21
22
# File 'lib/tcp.rb', line 20

def post_init
  start_tls(:verify_peer => true) if @connection.options[:secure]
end

#read(len, &cb) ⇒ Object



41
42
43
44
45
46
# File 'lib/tcp.rb', line 41

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

#receive_data(data) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
# File 'lib/tcp.rb', line 29

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



61
62
63
64
# File 'lib/tcp.rb', line 61

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

#startObject



48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/tcp.rb', line 48

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



66
67
68
# File 'lib/tcp.rb', line 66

def unbind
  @connection.onclose
end