This is the asynchronous version of connect.
You may wish to prefer the asynchronous version even in synchronous command line programs because, since 2.60, it implements RFC 8305 "Happy Eyeballs" recommendations to work around long connection timeouts in networks where IPv6 is broken by performing an IPv4 connection simultaneously without waiting for IPv6 to time out, which is not supported by the synchronous call. (This is not an API guarantee, and may change in the future.)
When the operation is finished callback
will be called. You can then call connect_async.end to
get the result of the operation.
Example: Socket client, async:
public class AsyncDemo : Object {
private MainLoop loop;
public AsyncDemo (MainLoop loop) {
this.loop = loop;
}
public async void http_request () throws Error {
try {
// Resolve hostname to IP address:
Resolver resolver = Resolver.get_default ();
List<InetAddress> addresses = yield resolver.lookup_by_name_async ("www.google.com");
InetAddress address = addresses.nth_data (0);
print ("Resolved www.google.com to %s\n", address.to_string ());
// Connect:
InetSocketAddress socket_address = new InetSocketAddress (address, 80);
SocketClient client = new SocketClient ();
SocketConnection conn = yield client.connect_async (socket_address);
print ("Connected to www.google.com\n");
// Send HTTP GET request
string message = "GET / HTTP/1.1\r\nHost: www.google.com\r\n\r\n";
yield conn.output_stream.write_async (message.data, Priority.DEFAULT);
print ("Wrote request\n");
// Receive response
DataInputStream input = new DataInputStream (conn.input_stream);
message = yield input.read_line_async ();
print ("Received status line: %s\n", message._strip ());
} catch (Error e) {
stderr.printf ("%s\n", e.message);
}
this.loop.quit ();
}
}
void main () {
var loop = new MainLoop ();
var demo = new AsyncDemo (loop);
demo.http_request.begin ();
loop.run ();
}
valac --pkg gio-2.0 GLib.SocketClient.connect_async.vala
this | |
connectable |
a SocketConnectable specifying the remote address. |
cancellable |
a Cancellable, or null |
callback | |
user_data |
user data for the callback |