Guest User

Untitled

a guest
Feb 20th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. using GLib;
  2. using NetHelper;
  3.  
  4. public class Example.FetchPage {
  5. MainLoop main_loop;
  6.  
  7. public FetchPage (string url) {
  8. // create our main loop
  9. main_loop = new MainLoop (null, false);
  10.  
  11. // create a new task queue. you probably only need one of
  12. // these per application, unless you want varying degrees
  13. // of scheduling.
  14. var task_queue = new TaskQueue ();
  15.  
  16. // queue the result of the fetch_page_async function
  17. task_queue.queue_iterable (
  18. // start to fetch the page asynchronously. when the
  19. // task is complete, our callback is executed, which
  20. // will kill the main loop.
  21. fetch_page_async (url).set_callback ((task, result) => {
  22. main_loop.quit ();
  23. })
  24. );
  25.  
  26. // start the main loop while we wait for processing to finish
  27. main_loop.run ();
  28. }
  29.  
  30. // this is the synchronous version. it just gets the tasks from
  31. // the async version, and calls run on them synchronously.
  32. // after all the tasks have been run, it returns the result.
  33. char* fetch_page (string url) {
  34. var iterator = fetch_page_async (url);
  35. while (iterator.next ()) {
  36. iterator.get ().run ();
  37. return (char*) iterator.get ().result;
  38. }
  39.  
  40. Iterable<Task> fetch_page_async (string url) {
  41. // get the hostname portion of the url
  42. var remote_host = NetHelper.get_http_host (url);
  43.  
  44. // NetHelper.get_host_addr returns a task, lets yield it.
  45. // When the function re-enters, the tasks result will be
  46. // our remote addr.
  47. var remote_addr = yield NetHelper.get_host_addr (remote_host);
  48.  
  49. // yield a task that finishes when a new socket/connect
  50. // has finished. at that point, we have a stream to work with.
  51. var stream = yield NetHelper.get_stream (remote_addr, 80);
  52.  
  53. // get the path portion, this is a blocking call (no yield)
  54. var path = NetHelper.get_http_path (url);
  55.  
  56. stream.write ("GET %s HTTP/1.0\r\n".printf (path));
  57. stream.write ("Host: %s\r\n\r\n".printf (remote_host));
  58. stream.flush ();
  59.  
  60. // wait for a buffer to be returned
  61. var result = yield stream.read ();
  62. }
  63.  
  64. static void main (string[] args) {
  65. new FetchPage (args[1]);
  66. }
  67. }
Add Comment
Please, Sign In to add comment