using Logger; using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net.Sockets; using System.Threading; using UnityEngine; namespace Networkreader { public abstract class AbstractNWReader { /// /// The IPAdress of the tcp Server. /// protected string IpAdress { get; set; } /// /// The port of the tcp Server. /// protected int Port { get; set; } /// /// The instance of the connected to : /// protected TcpClient Client { get; set; } /// /// The instance of the Network stream used for reading; /// protected NetworkStream NWStream{ get; set; } /// /// Identifies if the stream is still running or not. /// protected bool Streaming { get; set; } public AbstractNWReader(string ipAdress, int port) { this.IpAdress = ipAdress; this.Port = port; } /// /// Writes the data to the underlying file. /// /// Filepath of the .bin file. protected abstract void WriteToFileThread(object filepath); /// /// Get the filename the specific readr should write to /// protected abstract string GetFilename(); protected virtual void ReadBuffer(byte[] buffer) { int alreadyRead = 0; while (alreadyRead < buffer.Length) alreadyRead += NWStream.Read(buffer, alreadyRead, buffer.Length); } /// /// Stops the NWReader. /// public void StopReading() { Streaming = false; } /// /// Start the NW reader, /// /// The filename the data will be written to. public virtual string StartNWRead() { string filename = GetFilename(); string filePath = "./Assets/CSVInput/" + filename; try { Client = new TcpClient(); if (!Client.ConnectAsync(IpAdress, Port).Wait(1000)) return ""; File.Create(filePath).Close(); Thread th = new Thread(WriteToFileThread); th.Start(filePath); } catch (Exception e) { CityLogger.LogError("Unable to connect to server or start reading thread. Error: " + e.Message); filePath = string.Empty; } return filename; } } }