Class: Citrus::Connectors::WsConnector

Inherits:
Object
  • Object
show all
Includes:
Utils::EventEmitter
Defined in:
lib/citrus/connectors/ws_connector.rb

Overview

WsConnector

Instance Method Summary collapse

Methods included from Utils::EventEmitter

#emit, #on, #once

Constructor Details

#initialize(port, host, args = {}) ⇒ WsConnector

Create a new websocket connector

Parameters:

  • port (Integer)
  • host (String)
  • args (Hash) (defaults to: {})


25
26
27
28
29
30
31
32
33
34
35
# File 'lib/citrus/connectors/ws_connector.rb', line 25

def initialize port, host, args={}
  @port = port
  @host = host
  @args = args

  @heartbeats = args[:heartbeats] || true
  @heartbeat_timeout = args[:heartbeat_timeout] || 0.06
  @heartbeat_interval = args[:heartbeat_interval] || 0.025

  @cur_id = 0
end

Instance Method Details

#decode(msg) ⇒ Object

Decode message

Parameters:

  • msg (String)


79
80
81
82
83
84
# File 'lib/citrus/connectors/ws_connector.rb', line 79

def decode msg
  begin
    JSON.parse msg
  rescue => err
  end
end

#encode(req_id, route, msg) ⇒ Object

Encode message

Parameters:

  • req_id (Integer, NilClass)
  • route (String)
  • msg (Object)


68
69
70
71
72
73
74
# File 'lib/citrus/connectors/ws_connector.rb', line 68

def encode req_id, route, msg
  if req_id
    compose_response req_id, route, msg
  else
    componse_push route, msg
  end
end

#start(&block) ⇒ Object

Start the connector to listen to the specified port



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/citrus/connectors/ws_connector.rb', line 38

def start &block
  begin
    @server = WebSocket::EventMachine::Server.start(:host => @host, :port => @port) { |ws|
      ws.onopen {
        ws_socket = WsSocket.new @cur_id, ws
        @cur_id += 1
        emit :connection, ws_socket
        ws_socket.on(:closing) { |reason|
          ws_socket.send({ 'route' => 'on_kick', 'reason' => reason })
        }
      }
    }
  rescue => err
  end
  EM.next_tick { block_given? and yield }
end

#stop(force = false, &block) ⇒ Object

Stop the connector

Parameters:

  • force (Boolean) (defaults to: false)


58
59
60
61
# File 'lib/citrus/connectors/ws_connector.rb', line 58

def stop force=false, &block
  @server.close
  EM.next_tick { block_given? and yield }
end