Class: Meshchat::Network::Local::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/meshchat/network/local/connection.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(dispatcher, message_factory) ⇒ Connection

Returns a new instance of Connection.



10
11
12
13
14
15
16
# File 'lib/meshchat/network/local/connection.rb', line 10

def initialize(dispatcher, message_factory)
  @_message_factory = message_factory
  @_message_dispatcher = dispatcher

  # async, won't prevent us from sending
  start_server
end

Instance Attribute Details

#_message_dispatcherObject (readonly)

Returns the value of attribute _message_dispatcher.



8
9
10
# File 'lib/meshchat/network/local/connection.rb', line 8

def _message_dispatcher
  @_message_dispatcher
end

#_message_factoryObject (readonly)

Returns the value of attribute _message_factory.



8
9
10
# File 'lib/meshchat/network/local/connection.rb', line 8

def _message_factory
  @_message_factory
end

Instance Method Details

#create_http_request(location, payload, &error_callback) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/meshchat/network/local/connection.rb', line 33

def create_http_request(location, payload, &error_callback)
  # TODO: what about https?
  #       maybe do the regex match: /https?:\/\//
  location = 'http://' + location unless location.include?('http://')
  http = EventMachine::HttpRequest.new(location).post(
    body: payload,
    head: {
      'Accept' => 'application/json',
      'Content-Type' => 'application/json'
    }
  )

  http.errback &error_callback
  # example things available in the callback
  # p http.response_header.status
  # p http.response_header
  # p http.response
  http.callback { Display.debug http.response_header.status }
end

#payload_for(encrypted_message) ⇒ Object



53
54
55
# File 'lib/meshchat/network/local/connection.rb', line 53

def payload_for(encrypted_message)
  { message: encrypted_message }.to_json
end

#send_message(node, encrypted_message, &error_callback) ⇒ Object

Parameters:

  • node (Node)
    • the node describing the person you’re sending a message to

  • encrypted_message (JSON)
    • the message intended for the person at the location

  • error_callback (Block)
    • what to do in case of failure



28
29
30
31
# File 'lib/meshchat/network/local/connection.rb', line 28

def send_message(node, encrypted_message, &error_callback)
  payload = payload_for(encrypted_message)
  create_http_request(node.location_on_network, payload, &error_callback)
end

#start_serverObject



18
19
20
21
22
23
# File 'lib/meshchat/network/local/connection.rb', line 18

def start_server
  port = APP_CONFIG.user['port']
  Display.info "listening on port #{port}"
  EM.start_server('0.0.0.0', port,
    Network::Local::Server, _message_dispatcher)
end