TcpClientCommunication.cs 2.64 KB
using HHECS.BllModel;
using System.Net.Sockets;
using System.Text;

namespace HHECS.DAQClient.Communications
{
    public class TcpClientCommunication : ICommunication
    {
        public int CommunicationId { get; set; }

        public string IpAddress => _ipAddress;

        protected TcpClient tcpClient = new();

        protected string _ipAddress = null!;

        protected int _port;

        protected byte[] _data = new byte[1024 * 8];

        protected TcpClientCommunication() { }

        public TcpClientCommunication(int communicationId, string ip, int port) : this()
        {
            CommunicationId = communicationId;
            _ipAddress = ip;
            _port = port;
        }

        public BllResult ConnectClose()
        {
            try
            {
                tcpClient.Close();
                return BllResultFactory.Success();
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error(ex.Message);
            }
        }

        public BllResult ConnectServer()
        {
            try
            {
                tcpClient = new TcpClient();
                tcpClient.Connect(_ipAddress, _port);
                Task.Run(async () =>
                {
                    try
                    {
                        while (tcpClient.Connected)
                        {
                            var stream = tcpClient.GetStream();
                            var buffer = new byte[_data.Length];
                            stream.Read(buffer);
                            var bufferString = Encoding.Default.GetString(buffer).TrimEnd('\0');
                            if (!string.IsNullOrWhiteSpace(bufferString))
                            {
                                _data = buffer;
                            }
                            await Task.Delay(100);
                        }
                    }
                    catch (Exception) { }
                });
                return BllResultFactory.Success();
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error(ex.Message);
            }
        }

        public virtual BllResult Read(IEnumerable<DataItem> dataItems)
        {
            throw new NotImplementedException();
        }

        public BllResult Read(DataItem dataItem)
        {
           return Read([dataItem]);
        }

        public virtual BllResult Write(IEnumerable<DataItem> dataItems)
        {
            throw new NotImplementedException();
        }

        public BllResult Write(DataItem dataItem)
        {
           return Write([dataItem]);
        }
    }
}