class Async::WebSocket::Client

This is a basic synchronous websocket client:

Public Class Methods

connect(endpoint, *args, **options) { |connection| ... } click to toggle source

@return [Connection] an open websocket connection to the given endpoint.

# File lib/async/websocket/client.rb, line 51
def self.connect(endpoint, *args, **options, &block)
        client = self.open(endpoint, *args)
        connection = client.connect(endpoint.authority, endpoint.path, **options)
                
        return connection unless block_given?
                
        begin
                yield connection
        ensure
                connection.close
                client.close
        end
end
new(client, **options) click to toggle source
Calls superclass method
# File lib/async/websocket/client.rb, line 65
def initialize(client, **options)
        super(client)
        
        @options = options
end
open(endpoint, **options) { |client| ... } click to toggle source

@return [Client] a client which can be used to establish websocket connections to the given endpoint.

# File lib/async/websocket/client.rb, line 38
def self.open(endpoint, **options, &block)
        client = self.new(HTTP::Client.new(endpoint, **options), mask: true)
        
        return client unless block_given?
        
        begin
                yield client
        ensure
                client.close
        end
end

Public Instance Methods

connect(authority, path, headers: nil, handler: Connection, **options, &block) click to toggle source
# File lib/async/websocket/client.rb, line 89
def connect(authority, path, headers: nil, handler: Connection, **options, &block)
        headers = ::Protocol::HTTP::Headers[headers]
        request = Request.new(nil, authority, path, headers, **options)
        
        pool = @delegate.pool
        connection = pool.acquire
        
        response = request.call(connection)
        
        unless response.stream?
                raise ProtocolError, "Failed to negotiate connection: #{response.status}"
        end
        
        protocol = response.headers[SEC_WEBSOCKET_PROTOCOL]&.first
        stream = response.stream
        response = nil
        
        framer = Framer.new(pool, connection, stream)
        connection = nil
        
        handler.call(framer, protocol, **@options, &block)
ensure
        pool.release(connection) if connection
end