| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356 | 
							- using Aitex.Core.RT.Log;
 
- using Aitex.Core.Utilities;
 
- using DocumentFormat.OpenXml.ExtendedProperties;
 
- using System;
 
- using System.Collections.Generic;
 
- using System.Linq;
 
- using System.Net;
 
- using System.Net.Sockets;
 
- using System.Text;
 
- using System.Threading;
 
- using System.Threading.Tasks;
 
- namespace MECF.Framework.Common.Net
 
- {
 
-     public class JetTcpClient
 
-     {
 
-         #region 内部变量
 
-         private string _ip="127.0.0.1";
 
-         private int _port = 9600;
 
-         private bool _connected = false;
 
-         protected int _reconnectInterval = 500;
 
-         protected DateTime _connectTime = DateTime.Now;
 
-         private int _connectTimeout = 2000;
 
-         private int _receiveTimeout = 1000;
 
-         private int _sendTimeout = 1000;
 
-         private object _connectLocker=new object();
 
-         private object _reconnectLocker = new object();
 
-         private object _sendLocker = new object();
 
-         private object _receiveLocker = new object();
 
-         private object _closeLocker = new object();
 
-         private AutoResetEvent _connectAutoResetEvent=new AutoResetEvent(false);
 
-         private Socket _socket = null;
 
-         private bool _logEnabled;
 
-         private string _name;
 
-         private eEvent _eventId;
 
-         #endregion
 
-         #region 属性
 
-         /// <summary>
 
-         /// 重连间隔时长
 
-         /// </summary>
 
-         public int ReconnectInterval { set { _reconnectInterval = value; } }
 
-         /// <summary>
 
-         /// 连接超时时长
 
-         /// </summary>
 
-         public int ConnectTimeout { set { _connectTimeout = value; } }
 
-         /// <summary>
 
-         /// 接收超时时长
 
-         /// </summary>
 
-         public int ReceiveTimeout { set { _receiveTimeout = value; } }
 
-         /// <summary>
 
-         /// 发送超时时长
 
-         /// </summary>
 
-         public int SendTimeout { set { _sendTimeout = value; } }
 
-         /// <summary>
 
-         /// 连接状态
 
-         /// </summary>
 
-         public bool Connected { get { return _connected; } }
 
-         /// <summary>
 
-         /// 是否启用LOG
 
-         /// </summary>
 
-         public bool LogEnabled { set { _logEnabled=value; }}
 
-         /// <summary>
 
-         /// 名称
 
-         /// </summary>
 
-         public string Name { set { _name=value; } }
 
-         /// <summary>
 
-         /// 事件Id
 
-         /// </summary>
 
-         public eEvent EventId { set { _eventId = value; } }
 
-         #endregion
 
-         /// <summary>
 
-         /// 构造函数
 
-         /// </summary>
 
-         /// <param name="ip"></param>
 
-         /// <param name="port"></param>
 
-         public JetTcpClient(string ip,int port)
 
-         {
 
-             _ip= ip;
 
-             _port= port;
 
-         }
 
-         /// <summary>
 
-         /// 连接
 
-         /// </summary>
 
-         public NetResult Connect()
 
-         {
 
-             if (_connected)
 
-             {
 
-                 return NetResult.CreateSuccessResult();
 
-             }
 
-             if(!Monitor.TryEnter(_connectLocker,_connectTimeout))
 
-             {
 
-                 return NetResult.CreateFailedResult(NetErrorCode.LockerOccupied);
 
-             }
 
-             _connectTime = DateTime.Now;
 
-             _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 
-             _socket.ReceiveTimeout = _receiveTimeout;
 
-             _socket.SendTimeout=_sendTimeout;
 
-             NetStateObject stateObject=new NetStateObject();
 
-             stateObject.Socket = _socket;
 
-             stateObject.AutoResetEvent = _connectAutoResetEvent;
 
-             EndPoint localEndpoint = _socket.LocalEndPoint;
 
-             if(IPAddress.TryParse(_ip,out IPAddress ipAddress))
 
-             {
 
-                 try
 
-                 {
 
-                     _socket.BeginConnect(new IPEndPoint(ipAddress, _port), new AsyncCallback(ConnectCallBack), stateObject);
 
-                 }
 
-                 catch(Exception ex)
 
-                 {
 
-                     stateObject.Dispose();
 
-                     stateObject = null;
 
-                     ConnectFailedBusiness();
 
-                     Monitor.Exit(_connectLocker);
 
-                     return NetResult.CreateFailedResult((int)NetErrorCode.InnerException, ex.Message);
 
-                 }
 
-                 if (!_connectAutoResetEvent.WaitOne(_connectTimeout))
 
-                 {
 
-                     stateObject.Dispose();
 
-                     stateObject = null;
 
-                     ConnectFailedBusiness();
 
-                     Monitor.Exit(_connectLocker);
 
-                     return NetResult.CreateFailedResult(NetErrorCode.ConnectTimeout);
 
-                 }
 
-                 
 
-                 LOG.WriteLog(eEvent.EV_DEVICE_INFO, "System", $"Connect {_ip}:{_port} Success,local {localEndpoint}");
 
-                 _connected = true;
 
-                 stateObject.Dispose();
 
-                 stateObject = null;
 
-                 Monitor.Exit(_connectLocker);
 
-                 return NetResult.CreateSuccessResult();
 
-             }
 
-             else
 
-             {
 
-                 stateObject.Dispose();
 
-                 stateObject = null;
 
-                 ConnectFailedBusiness();
 
-                 Monitor.Exit(_connectLocker);
 
-                 return NetResult.CreateFailedResult(NetErrorCode.InvalidIpAddress);
 
-             }
 
-         }
 
-         /// <summary>
 
-         /// 中止
 
-         /// </summary>
 
-         public void Stop()
 
-         {
 
-             CloseSocket();
 
-         }
 
-         /// <summary>
 
-         /// 连接失败后处理
 
-         /// </summary>
 
-         /// <param name="stateObject"></param>
 
-         private void ConnectFailedBusiness()
 
-         {            
 
-             _connectAutoResetEvent.Reset();
 
-             CloseSocket();
 
-         }
 
-         /// <summary>
 
-         /// 关闭Socket
 
-         /// </summary>
 
-         private void CloseSocket()
 
-         {
 
-             if (Monitor.TryEnter(_closeLocker, 10))
 
-             {
 
-                 if (_socket != null)
 
-                 {
 
-                     try
 
-                     {
 
-                         _socket.Shutdown(SocketShutdown.Both);
 
-                     }
 
-                     catch
 
-                     {
 
-                     }
 
-                     try
 
-                     {
 
-                         _socket.Close();
 
-                     }
 
-                     catch
 
-                     {
 
-                     }
 
-                     _socket = null;
 
-                     _connected = false;
 
-                 }
 
-                 Monitor.Exit(_closeLocker);
 
-             }
 
-         }
 
-         /// <summary>
 
-         /// 当连接的结果返回
 
-         /// </summary>
 
-         /// <param name="ar">异步对象</param>
 
-         private void ConnectCallBack(IAsyncResult ar)
 
-         {
 
-             if (ar.AsyncState is NetStateObject state)
 
-             {
 
-                 if (state.Socket != null)
 
-                 {
 
-                     try
 
-                     {
 
-                         state.Socket.EndConnect(ar);
 
-                         state.AutoResetEvent.Set();
 
-                     }
 
-                     catch (Exception ex)
 
-                     {
 
-                     }
 
-                 }
 
-             }
 
-         }
 
-         /// <summary>
 
-         /// 写日志
 
-         /// </summary>
 
-         /// <param name="bytes"></param>
 
-         /// <param name="logType"></param>
 
-         private void WriteInfoLog(byte[] bytes,int logType)
 
-         {
 
-             if (_logEnabled)
 
-             {
 
-                 string str = string.Join(" ", Array.ConvertAll(bytes, x => x.ToString("X2")));
 
-                 string type = logType == 0 ? "receive" : "send";
 
-                 LOG.WriteBackgroundLog(_eventId, _name, $"{type} {str}");
 
-             }
 
-         }
 
-         /// <summary>
 
-         /// 发送数据
 
-         /// </summary>
 
-         /// <param name="data"></param>
 
-         /// <returns></returns>
 
-         public NetResult Send(byte[] data)
 
-         {
 
-             if(!Connected)
 
-             {
 
-                 return NetResult.CreateFailedResult(NetErrorCode.NetOffline);
 
-             }
 
-             //清除缓存数据
 
-             ClearPreData();
 
-             //进入发送
 
-             if (Monitor.TryEnter(_sendLocker,_sendTimeout))
 
-             {
 
-                 if(_socket==null)
 
-                 {
 
-                     return NetResult.CreateFailedResult(NetErrorCode.NullSocketObject);
 
-                 }
 
-                 try
 
-                 {
 
-                     _socket.Send(data);
 
-                     WriteInfoLog(data, 1);
 
-                     Monitor.Exit(_sendLocker);
 
-                     return NetResult.CreateSuccessResult();
 
-                 }
 
-                 catch (Exception ex)
 
-                 {
 
-                     Monitor.Exit(_sendLocker);
 
-                     ConnectFailedBusiness();
 
-                     return NetResult.CreateFailedResult((int)NetErrorCode.InnerException, ex.Message);
 
-                 }
 
-             }
 
-             else
 
-             {
 
-                 return NetResult.CreateFailedResult(NetErrorCode.GetLockTimeout);
 
-             }
 
-         }
 
-         /// <summary>
 
-         /// 接收数据
 
-         /// </summary>
 
-         /// <param name="length"></param>
 
-         /// <returns></returns>
 
-         public NetResult<byte[]> Receive(int length)
 
-         {
 
-             if (!Connected)
 
-             {
 
-                 return NetResult.CreateFailedResult<byte[]>(NetErrorCode.NetOffline);
 
-             }
 
-             if (Monitor.TryEnter(_receiveLocker,_receiveTimeout))
 
-             {
 
-                 if(_socket==null)
 
-                 {
 
-                     return NetResult.CreateFailedResult<byte[]>(NetErrorCode.NullSocketObject);
 
-                 }
 
-                 try
 
-                 {
 
-                     byte[] buffer = null;
 
-                     if (length == -1)
 
-                     {
 
-                         buffer = new byte[_socket.Available];
 
-                     }
 
-                     else
 
-                     {
 
-                         buffer = new byte[length];
 
-                     }
 
-                     _socket.Receive(buffer, length, SocketFlags.None);
 
-                     WriteInfoLog(buffer, 0);
 
-                     Monitor.Exit(_receiveLocker);
 
-                     return NetResult.CreateSuccessResult<byte[]>(buffer);
 
-                 }
 
-                 catch(SocketException ex)
 
-                 {
 
-                     Monitor.Exit(_receiveLocker);
 
-                     ConnectFailedBusiness();
 
-                     return NetResult.CreateFailedResult<byte[]>((int)NetErrorCode.InnerException, ex.Message);
 
-                 }
 
-                 catch (Exception ex)
 
-                 {
 
-                     Monitor.Exit(_receiveLocker);
 
-                     ConnectFailedBusiness();
 
-                     return NetResult.CreateFailedResult<byte[]>((int)NetErrorCode.InnerException, ex.Message);
 
-                 }
 
-             }
 
-             else
 
-             {
 
-                 return NetResult.CreateFailedResult<byte[]>(NetErrorCode.GetLockTimeout);
 
-             }
 
-         }
 
-         /// <summary>
 
-         /// 清除先前的数据
 
-         /// </summary>
 
-         public void ClearPreData()
 
-         {
 
-             if (!Connected)
 
-             {
 
-                 return;
 
-             }
 
-             if (Monitor.TryEnter(_receiveLocker, _receiveTimeout))
 
-             {
 
-                 if (_socket == null)
 
-                 {
 
-                     return;
 
-                 }
 
-                 try
 
-                 {
 
-                     while (_socket.Available != 0)
 
-                     {
 
-                         byte[] buffer = new byte[_socket.Available];
 
-                         _socket.Receive(buffer, buffer.Length, SocketFlags.None);
 
-                     }
 
-                     Monitor.Exit(_receiveLocker);
 
-                 }
 
-                 catch (SocketException ex)
 
-                 {
 
-                     Monitor.Exit(_receiveLocker);
 
-                     ConnectFailedBusiness();
 
-                 }
 
-                 catch (Exception ex)
 
-                 {
 
-                     Monitor.Exit(_receiveLocker);
 
-                     ConnectFailedBusiness();
 
-                 }
 
-             }
 
-         }
 
-     }
 
- }
 
 
  |