MainThread.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using AggregatorFinal.DataAggregator;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.Sockets;
  8. using System.Text;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. namespace AggregatorFinal.Rec
  12. {
  13. class MainThread
  14. {
  15. Thread _thread;
  16. String ip;
  17. string port;
  18. public MainThread(String ip, string port)
  19. {
  20. this.port = port;
  21. this.ip = ip;
  22. _thread = new Thread(threadFunction);
  23. _thread.Start();
  24. }
  25. private void threadFunction()
  26. {
  27. try
  28. {
  29. char[] splitter = { '#' };
  30. UDP_Receiver _udp_Receiver = new UDP_Receiver(port);
  31. while (true)
  32. {
  33. string text = _udp_Receiver.receiveMessage();
  34. String[] parts2 = text.Split(splitter, StringSplitOptions.None);
  35. String senderIp = parts2[0];
  36. String senderPort = parts2[1];
  37. String fileName = parts2[2];
  38. DirectoryInfo di = Directory.CreateDirectory(Aggregator.resultFolder + "/" + senderIp);
  39. int freePort = FreeTcpPort();
  40. new RecThread(di.FullName + "/" + fileName, freePort);
  41. Console.WriteLine("Rec file: " + fileName + ", from: " + senderIp);
  42. UDP_Sender.forwardMessage(senderIp, senderPort, "RequestFile" + "#" + fileName + ":" + ip + ":" + freePort);
  43. }
  44. }
  45. catch (Exception es)
  46. {
  47. Console.WriteLine(es.Message);
  48. }
  49. }
  50. static int FreeTcpPort()
  51. {
  52. TcpListener l = new TcpListener(IPAddress.Loopback, 0);
  53. l.Start();
  54. int port = ((IPEndPoint)l.LocalEndpoint).Port;
  55. l.Stop();
  56. return port;
  57. }
  58. }
  59. }