Discoverer.vala 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using LibPeer.Networks.Simulation;
  2. using LibPeer.Protocols.Mx2;
  3. using LibPeer.Protocols.Gdp;
  4. using LibPeer.Protocols.Stp;
  5. using LibPeer.Networks;
  6. using Gee;
  7. namespace Discoverer {
  8. class DiscoverWorker : Object {
  9. private Muxer muxer = new Muxer();
  10. private Network network;
  11. private GeneralDiscoveryProtocol discovery;
  12. private GdpApplication discovery_app;
  13. private StreamTransmissionProtocol stp;
  14. private Instance app_instance;
  15. private int id;
  16. public DiscoverWorker(int id, Network net) throws Error, IOError {
  17. this.id = id;
  18. network = net;
  19. network.bring_up();
  20. print("Instansiate GDP\n");
  21. discovery = new GeneralDiscoveryProtocol(muxer);
  22. print("Add network\n");
  23. discovery.add_network(network);
  24. print("Setup application instance\n");
  25. app_instance = muxer.create_instance("discovery_toy");
  26. app_instance.incoming_greeting.connect(greeted_by_peer);
  27. discovery_app = discovery.add_application (app_instance);
  28. discovery_app.query_answered.connect(query_answered);
  29. var ch = discovery_app.create_app_challenge();
  30. var ch2 = new Challenge.from_values(ch.public_key, ch.challenge_blob);
  31. print(@"Solved own challenge: $(discovery_app.solve_app_challenge(ch2))\n");
  32. print("Instansiate STP\n");
  33. stp = new StreamTransmissionProtocol(muxer, app_instance);
  34. stp.incoming_stream.connect(ingress_stream_established);
  35. print("Querying\n");
  36. discovery.query_general(discovery_app);
  37. }
  38. private void query_answered(Answer answer) {
  39. print("[GOAL!] I received a query answer!\n");
  40. if(answer.query_summary.is_null_resource()) {
  41. muxer.inquire(app_instance, answer.instance_reference, answer.connection_methods);
  42. }
  43. }
  44. private void greeted_by_peer(InstanceReference origin) {
  45. print("[GOAL!] I received a greeting!\n");
  46. stp.initialise_stream(origin).established.connect(egress_stream_established);
  47. }
  48. private void egress_stream_established(OutputStream stream) {
  49. print("[GOAL!] I established an egress stream to a peer!\n");
  50. stream.write(new uint8[] { 13, 'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!'});
  51. stream.close();
  52. }
  53. private void ingress_stream_established(InputStream stream) {
  54. print("[GOAL!] An ingress stream has been established!\n");
  55. var message_size = new uint8[1];
  56. stream.read(message_size);
  57. var message = new uint8[message_size[0]];
  58. stream.read(message);
  59. stream.close();
  60. var message_str = new LibPeer.Util.ByteComposer().add_byte_array(message).to_string();
  61. print(@"[GOAL!] I received a message from a peer: '$(message_str)'\n");
  62. }
  63. }
  64. }