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:

Defined Under Namespace

Classes: Framer

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client, **options) ⇒ Client

Returns a new instance of Client.



65
66
67
68
69
# File 'lib/async/websocket/client.rb', line 65

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

Class Method Details

.connect(endpoint, *args, **options, &block) ⇒ Connection

Returns an open websocket connection to the given endpoint.

Returns:

  • (Connection)

    an open websocket connection to the given endpoint.



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

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

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

Returns a client which can be used to establish websocket connections to the given endpoint.

Returns:

  • (Client)

    a client which can be used to establish websocket connections to the given endpoint.



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

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: nil, handler: Connection, **options, &block) ⇒ Object



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/async/websocket/client.rb', line 89

def connect(path, headers: nil, handler: Connection, **options, &block)
	headers = ::Protocol::HTTP::Headers[headers]
	request = Request.new(nil, nil, 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
	framer = Framer.new(pool, connection, response.stream)
	
	handler.call(framer, protocol, **@options, &block)
end