Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using GLib;
- using NetHelper;
- public class Example.FetchPage {
- MainLoop main_loop;
- public FetchPage (string url) {
- // create our main loop
- main_loop = new MainLoop (null, false);
- // create a new task queue. you probably only need one of
- // these per application, unless you want varying degrees
- // of scheduling.
- var task_queue = new TaskQueue ();
- // queue the result of the fetch_page_async function
- task_queue.queue_iterable (
- // start to fetch the page asynchronously. when the
- // task is complete, our callback is executed, which
- // will kill the main loop.
- fetch_page_async (url).set_callback ((task, result) => {
- main_loop.quit ();
- })
- );
- // start the main loop while we wait for processing to finish
- main_loop.run ();
- }
- // this is the synchronous version. it just gets the tasks from
- // the async version, and calls run on them synchronously.
- // after all the tasks have been run, it returns the result.
- char* fetch_page (string url) {
- var iterator = fetch_page_async (url);
- while (iterator.next ()) {
- iterator.get ().run ();
- return (char*) iterator.get ().result;
- }
- Iterable<Task> fetch_page_async (string url) {
- // get the hostname portion of the url
- var remote_host = NetHelper.get_http_host (url);
- // NetHelper.get_host_addr returns a task, lets yield it.
- // When the function re-enters, the tasks result will be
- // our remote addr.
- var remote_addr = yield NetHelper.get_host_addr (remote_host);
- // yield a task that finishes when a new socket/connect
- // has finished. at that point, we have a stream to work with.
- var stream = yield NetHelper.get_stream (remote_addr, 80);
- // get the path portion, this is a blocking call (no yield)
- var path = NetHelper.get_http_path (url);
- stream.write ("GET %s HTTP/1.0\r\n".printf (path));
- stream.write ("Host: %s\r\n\r\n".printf (remote_host));
- stream.flush ();
- // wait for a buffer to be returned
- var result = yield stream.read ();
- }
- static void main (string[] args) {
- new FetchPage (args[1]);
- }
- }
Add Comment
Please, Sign In to add comment