Class: Async::WebSocket::Client

Inherits:
Protocol::HTTP::Middleware
  • Object
show all
Includes:
Protocol::WebSocket::Headers
Defined in:
lib/async/websocket/client.rb

Overview

This is a basic synchronous websocket client:

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(delegate, **options) ⇒ Client

Returns a new instance of Client.



63
64
65
66
67
# File 'lib/async/websocket/client.rb', line 63

def initialize(delegate, **options)
  super(delegate)
  
  @options = options
end

Class Method Details

.connect(endpoint, *args, protocols: [], **options, &block) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/async/websocket/client.rb', line 49

def self.connect(endpoint, *args, protocols: [], **options, &block)
  self.open(endpoint, *args, **options) do |client|
    connection = client.connect(endpoint.path, protocols: protocols)
    
    return connection unless block_given?
    
    begin
      yield connection
    ensure
      connection.close
    end
  end
end

.open(endpoint, *args, &block) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
# File 'lib/async/websocket/client.rb', line 37

def self.open(endpoint, *args, &block)
  client = self.new(HTTP::Client.new(endpoint, *args), mask: endpoint.secure?)
  
  return client unless block_given?
  
  begin
    yield client
  ensure
    client.close
  end
end

Instance Method Details

#connect(path, headers: [], handler: Connection, **options) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/async/websocket/client.rb', line 69

def connect(path, headers: [], handler: Connection, **options)
  request = Request.new(nil, nil, path, headers, **options)
  
  response = self.call(request)
  
  unless response.stream?
    raise ProtocolError, "Failed to negotiate connection: #{response.status}"
  end
  
  protocol = response.headers[SEC_WEBSOCKET_PROTOCOL]&.first
  framer = Protocol::WebSocket::Framer.new(response.stream)
  
  connection = handler.call(framer, protocol, **@options)
  
  return connection unless block_given?
  
  begin
    yield connection
  ensure
    connection.close
  end
end