git_bsmd/AIS/bsmd.AIS2Service/SerialTCPReader.cs
2025-11-11 16:54:40 +01:00

81 lines
1.9 KiB
C#

using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace bsmd.AIS2Service
{
internal class SerialTCPReader : IAISThread
{
private readonly string _host;
private readonly uint _port;
private NetworkStream tcpStream;
private TcpClient tcpSocket;
private Thread _thread;
private static readonly ILog _log = LogManager.GetLogger(typeof(SerialTCPReader));
public SerialTCPReader(string host, uint port)
{
_host = host; _port = port;
}
private void ReadData()
{
try
{
while (true)
{
if (this.tcpSocket == null || !this.tcpSocket.Connected) this.Connect();
}
}
catch(Exception ex)
{
_log.ErrorFormat("Something bad has happened: {0}", ex.Message);
if(this.FatalErrorOccurred != null)
this.FatalErrorOccurred(this, new EventArgs());
}
}
private void Connect()
{
this.tcpSocket = new TcpClient(_host, (int)_port);
this.tcpStream = tcpSocket.GetStream();
_log.InfoFormat("TCP stream connected ({0}:{1})", _host, _port);
}
#region IAISThread implementation
public event EventHandler FatalErrorOccurred;
public void Start()
{
if (_thread != null) return; // may not run twice
ThreadStart runReader = new ThreadStart(this.ReadData);
_thread = new Thread(runReader);
}
public void Stop()
{
}
#endregion
}
}