OEMListener.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. listener.AcceptTcpClientAsync().ContinueWith(t =>
  41. {
  42. var connection = new OEMConnection(t.Result, Cache, Queue);
  43. lock (connectionsLock)
  44. {
  45. Connections.Add(connection);
  46. }
  47. connection.OnCompletion = () =>
  48. {
  49. // When the connection finishes, we should remove it from our list.
  50. lock (connectionsLock)
  51. {
  52. Connections.Remove(connection);
  53. }
  54. };
  55. connection.Run();
  56. // Accept a new client.
  57. AcceptClient();
  58. }, TaskContinuationOptions.OnlyOnRanToCompletion);
  59. }
  60. public void Stop()
  61. {
  62. listener.Stop();
  63. lock (connectionsLock)
  64. {
  65. // Running in parallel because each connection can take a second to stop.
  66. Parallel.ForEach(Connections, connection =>
  67. {
  68. connection.Stop();
  69. });
  70. Connections.Clear();
  71. }
  72. }
  73. }
  74. }