12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- 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
- {
- /// <summary>
- /// The IPAdress of the tcp Server.
- /// </summary>
- protected string IpAdress { get; set; }
- /// <summary>
- /// The port of the tcp Server.
- /// </summary>
- protected int Port { get; set; }
- /// <summary>
- /// The instance of the <see cref="TcpClient"/> connected to <see cref="IpAdress"/>:<see cref="Port"/>
- /// </summary>
- protected TcpClient Client { get; set; }
- /// <summary>
- /// The instance of the Network stream used for reading;
- /// </summary>
- protected NetworkStream NWStream{ get; set; }
- /// <summary>
- /// Identifies if the stream is still running or not.
- /// </summary>
- protected bool Streaming { get; set; }
- public AbstractNWReader(string ipAdress, int port)
- {
- this.IpAdress = ipAdress;
- this.Port = port;
- }
- /// <summary>
- /// Writes the data to the underlying file.
- /// </summary>
- /// <param name="filepath">Filepath of the .bin file.</param>
- protected abstract void WriteToFileThread(object filepath);
- /// <summary>
- /// Get the filename the specific readr should write to
- /// </summary>
- protected abstract string GetFilename();
- protected virtual void ReadBuffer(byte[] buffer)
- {
- int alreadyRead = 0;
- while (alreadyRead < buffer.Length)
- alreadyRead += NWStream.Read(buffer, alreadyRead, buffer.Length);
- }
- /// <summary>
- /// Stops the NWReader.
- /// </summary>
- public void StopReading()
- {
- Streaming = false;
- }
- /// <summary>
- /// Start the NW reader,
- /// </summary>
- /// <returns>The filename the data will be written to.</returns>
- 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;
- }
- }
- }
|