Class: AsyncCable::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/async_cable/server.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(connection_class:, &block) ⇒ Server

Returns a new instance of Server.

Parameters:

  • connection_class (Class)

    subclass of AsyncCable::Connection.

  • block (Proc<Hash>)

    yields when not valid WS request.

Yield Returns:

  • (Array)

    ‘[status,headers,body]`



13
14
15
16
# File 'lib/async_cable/server.rb', line 13

def initialize(connection_class:, &block)
  @connection_class = connection_class
  @block = block
end

Instance Attribute Details

#connection_classObject (readonly)

Rack application should be used inside Async::Reactor loop.



8
9
10
# File 'lib/async_cable/server.rb', line 8

def connection_class
  @connection_class
end

Instance Method Details

#call(env) ⇒ Array

Returns ‘[status,headers,body]`.

Parameters:

  • env (Hash)

Returns:

  • (Array)

    ‘[status,headers,body]`



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/async_cable/server.rb', line 20

def call(env)
  response = Async::WebSocket::Adapters::Rack.open(env, handler: connection_class) do |connection|
    connection.handle_open(env)

    while (data = connection.read)
      connection.on_data(data)
    end
  rescue Protocol::WebSocket::ProtocolError => error
    logger.debug { "#{self.class}#call rescue #{error.class} message=#{error.message} code=#{error.code}" }
    connection.close_code = error.code
    connection.close_reason = error.message
  rescue AsyncCable::Errors::Error => error
    connection.close_code = error.code
    connection.close_reason = error.message
  ensure
    logger.debug { "#{self.class}#call connection closed" }
    connection.handle_close
  end
  # response[1] ca be Protocol::HTTP::Headers::Merged here.
  # We transform it to hash because we don't want to break other middleware logic.
  response[1] = response[1].to_a.to_h if !response.nil? && !response[1].is_a?(Hash)
  response || [400, { 'Content-Type' => 'text/plain' }, ['Not valid ws']]
end

#loggerObject



44
45
46
# File 'lib/async_cable/server.rb', line 44

def logger
  AsyncCable.config.logger
end