class Async::Socket

def self.accept(*args, task: Task.current, &block)

Bind to a local address and accept connections in a loop.
def self.accept(*args, task: Task.current, &block)
	bind(*args, task: task) do |wrapper|
		task.with(*wrapper.accept, &block) while true
	end
end

def self.bind(local_address, backlog: nil, protocol: 0, task: Task.current, &block)

Options Hash: (**protcol)
  • The (Integer) -- socket protocol to use.

Parameters:
  • local_address (Addrinfo) -- The local address to bind to.
def self.bind(local_address, backlog: nil, protocol: 0, task: Task.current, &block)
	socket = ::Socket.new(local_address.afamily, local_address.socktype, protocol)
	
	socket.setsockopt(::Socket::SOL_SOCKET, ::Socket::SO_REUSEADDR, true)
	socket.bind(local_address)
	
	socket.listen(backlog) if backlog
	
	if block_given?
		task.with(socket, &block)
	else
		return socket
	end
end

def self.connect(remote_address, local_address = nil, protocol: 0, task: Task.current)

Options Hash: (**protcol)
  • The (Integer) -- socket protocol to use.

Parameters:
  • local_address (Addrinfo) -- The local address to bind to before connecting.
  • remote_address (Addrinfo) -- The remote address to connect to.
def self.connect(remote_address, local_address = nil, protocol: 0, task: Task.current)
	socket = ::Socket.new(remote_address.afamily, remote_address.socktype, protocol)
	
	if local_address
		socket.setsockopt(::Socket::SOL_SOCKET, ::Socket::SO_REUSEADDR, true)
		socket.bind(local_address) if local_address
	end
	
	if block_given?
		task.with(socket) do |wrapper|
			wrapper.connect(remote_address.to_sockaddr)
			
			yield wrapper
		end
	else
		task.bind(socket).connect(remote_address.to_sockaddr)
		
		return socket
	end
end