Async::BusSourceAsyncBusClient

class Client

Represents a client that can connect to a server.

Definitions

def initialize(endpoint = nil, **options)

Initialize a new client.

Signature

parameter endpoint IO::Endpoint

The endpoint to connect to.

parameter options Hash

Additional options for the connection.

Implementation

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

def connect(parent: Task.current)

Connect to the server.

Signature

parameter persist Boolean

Whether to keep the connection open indefiniely.

yields {|connection| ...}

If a block is given, it will be called with the connection, and the connection will be closed afterwards.

returns Protocol::Connection

The connection if no block is given.

Implementation

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

def run(&block)

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.

Signature

yields {|connection| ...}

If a block is given, it will be called with the connection.

returns Async::Task

The task that runs the client.

Implementation

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