Class: Async::Bus::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/async/bus/client.rb

Overview

Represents a client that can connect to a server.

Instance Method Summary collapse

Constructor Details

#initialize(endpoint = nil, **options) ⇒ Client

Initialize a new client.



16
17
18
19
# File 'lib/async/bus/client.rb', line 16

def initialize(endpoint = nil, **options)
	@endpoint = endpoint || Protocol.local_endpoint
	@options = options
end

Instance Method Details

#connect(parent: Task.current) ⇒ Object

Connect to the server.



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/async/bus/client.rb', line 42

def connect(parent: Task.current)
	connection = connect!
	
	connection_task = parent.async do
		connection.run
	end
	
	connected!(connection)
	
	return connection unless block_given?
	
	begin
		yield(connection, connection_task)
	ensure
		connection_task&.stop
		connection&.close
	end
end

#run(&block) ⇒ Object

Run the client in a loop, reconnecting if necessary.

Automatically reconnects when the connection fails, with random backoff. This is useful for long-running clients that need to maintain a persistent connection.



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

def run(&block)
	Async(transient: true) do |task|
		loop do
			connection = connect!
			
			connected_task = task.async do
				connected!(connection)
				
				yield(connection) if block_given?
			end
			
			connection.run
		rescue => error
			Console.error(self, "Connection failed:", exception: error)
			sleep(rand)
		ensure
			# Ensure any tasks that were created during connection are stopped:
			connected_task&.stop
			
			# Close the connection itself:
			connection&.close
		end
	end
end