OEMListener.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using Comal.Classes;
  2. using InABox.Core;
  3. using InABox.DigitalMatter;
  4. using NPOI.HSSF.Record.CF;
  5. using PRSServer.Engines;
  6. using System;
  7. using System.Collections.Concurrent;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Net;
  11. using System.Net.Sockets;
  12. using System.Text;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15. using System.Windows.Media.Media3D;
  16. namespace PRSServer
  17. {
  18. internal class OEMListener
  19. {
  20. private TcpListener listener;
  21. private GPSDeviceCache Cache;
  22. private GPSUpdateQueue Queue;
  23. private object connectionsLock = new object();
  24. private List<OEMConnection> Connections = new();
  25. public int Port { get; set; }
  26. public OEMListener(int port, GPSDeviceCache cache, GPSUpdateQueue queue)
  27. {
  28. Port = port;
  29. Cache = cache;
  30. Queue = queue;
  31. }
  32. public void Start()
  33. {
  34. listener = new TcpListener(IPAddress.Any, Port);
  35. listener.Start();
  36. AcceptClient();
  37. }
  38. private void AcceptClient()
  39. {
  40. Logger.Send(LogType.Information, "", "Waiting for client.");
  41. listener.AcceptTcpClientAsync().ContinueWith(t =>
  42. {
  43. try
  44. {
  45. Logger.Send(LogType.Information, "", "Client Connected");
  46. var connection = new OEMConnection(t.Result, Cache, Queue);
  47. lock (connectionsLock)
  48. {
  49. Connections.Add(connection);
  50. }
  51. connection.OnCompletion = () =>
  52. {
  53. // When the connection finishes, we should remove it from our list.
  54. lock (connectionsLock)
  55. {
  56. Connections.Remove(connection);
  57. }
  58. };
  59. connection.Run();
  60. // Accept a new client.
  61. //AcceptClient();
  62. }
  63. catch (Exception e)
  64. {
  65. Logger.Send(LogType.Error, "", CoreUtils.FormatException(e));
  66. }
  67. }, TaskContinuationOptions.OnlyOnRanToCompletion);
  68. }
  69. public void Stop()
  70. {
  71. listener.Stop();
  72. lock (connectionsLock)
  73. {
  74. // Running in parallel because each connection can take a second to stop.
  75. Parallel.ForEach(Connections, connection =>
  76. {
  77. connection.Stop();
  78. });
  79. Connections.Clear();
  80. }
  81. }
  82. }
  83. }