AbstractNWReader.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using Logger;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Net.Sockets;
  8. using System.Threading;
  9. using UnityEngine;
  10. namespace Networkreader
  11. {
  12. public abstract class AbstractNWReader
  13. {
  14. /// <summary>
  15. /// The IPAdress of the tcp Server.
  16. /// </summary>
  17. protected string IpAdress { get; set; }
  18. /// <summary>
  19. /// The port of the tcp Server.
  20. /// </summary>
  21. protected int Port { get; set; }
  22. /// <summary>
  23. /// The instance of the <see cref="TcpClient"/> connected to <see cref="IpAdress"/>:<see cref="Port"/>
  24. /// </summary>
  25. protected TcpClient Client { get; set; }
  26. /// <summary>
  27. /// The instance of the Network stream used for reading;
  28. /// </summary>
  29. protected NetworkStream NWStream{ get; set; }
  30. /// <summary>
  31. /// Identifies if the stream is still running or not.
  32. /// </summary>
  33. protected bool Streaming { get; set; }
  34. public AbstractNWReader(string ipAdress, int port)
  35. {
  36. this.IpAdress = ipAdress;
  37. this.Port = port;
  38. }
  39. /// <summary>
  40. /// Writes the data to the underlying file.
  41. /// </summary>
  42. /// <param name="filepath">Filepath of the .bin file.</param>
  43. protected abstract void WriteToFileThread(object filepath);
  44. /// <summary>
  45. /// Get the filename the specific readr should write to
  46. /// </summary>
  47. protected abstract string GetFilename();
  48. protected virtual void ReadBuffer(byte[] buffer)
  49. {
  50. int alreadyRead = 0;
  51. while (alreadyRead < buffer.Length)
  52. alreadyRead += NWStream.Read(buffer, alreadyRead, buffer.Length);
  53. }
  54. /// <summary>
  55. /// Stops the NWReader.
  56. /// </summary>
  57. public void StopReading()
  58. {
  59. Streaming = false;
  60. }
  61. /// <summary>
  62. /// Start the NW reader,
  63. /// </summary>
  64. /// <returns>The filename the data will be written to.</returns>
  65. public virtual string StartNWRead()
  66. {
  67. string filename = GetFilename();
  68. string filePath = "./Assets/CSVInput/" + filename;
  69. try
  70. {
  71. Client = new TcpClient();
  72. if (!Client.ConnectAsync(IpAdress, Port).Wait(1000))
  73. return "";
  74. File.Create(filePath).Close();
  75. Thread th = new Thread(WriteToFileThread);
  76. th.Start(filePath);
  77. }
  78. catch (Exception e)
  79. {
  80. CityLogger.LogError("Unable to connect to server or start reading thread. Error: " + e.Message);
  81. filePath = string.Empty;
  82. }
  83. return filename;
  84. }
  85. }
  86. }