def connect(address, **config):
ssl_context = make_ssl_context(**config)<EOL>last_error = None<EOL>log_debug("<STR_LIT>", address)<EOL>resolver = Resolver(custom_resolver=config.get("<STR_LIT>"))<EOL>resolver.addresses.append(address)<EOL>resolver.custom_resolve()<EOL>resolver.dns_resolve()<EOL>for resolved_address in resolver.addresses:<EOL><INDENT>try:<EOL><INDENT>s = _connect(resolved_address, **config)<EOL>s, der_encoded_server_certificate = _secure(s, address[<NUM_LIT:0>], ssl_context)<EOL>connection = _handshake(s, resolved_address, der_encoded_server_certificate, **config)<EOL><DEDENT>except Exception as error:<EOL><INDENT>last_error = error<EOL><DEDENT>else:<EOL><INDENT>return connection<EOL><DEDENT><DEDENT>if last_error is None:<EOL><INDENT>raise ServiceUnavailable("<STR_LIT>" % address)<EOL><DEDENT>else:<EOL><INDENT>raise last_error<EOL><DEDENT>
Connect and perform a handshake and return a valid Connection object, assuming
    a protocol version can be agreed.