using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; namespace Getf.Service.Transfer.Request.SDK { public class TcpClientService : IDisposable { private Socket _SocketClient; private readonly string _IP; private readonly int _Port; public event Action OnError; public event Action OnConnected; public event Action OnDataGeted; bool IsDisposed = false; public TcpClientService(string ip, int port) { _IP = ip; _Port = port; } public void Connect() { if (_SocketClient != null) { return; } _SocketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _SocketClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); IPAddress ipAddress = IPAddress.Parse(_IP); var endPoint = new IPEndPoint(ipAddress, _Port); _SocketClient.BeginConnect(endPoint, new AsyncCallback(Connected), null); } private void Connected(IAsyncResult asyncResult) { try { _SocketClient.EndConnect(asyncResult); TriggerConnected(); } catch (Exception e) { TriggerError(e.Message); } } public void ReceiveLoop(int times = -1) { Thread thread = new Thread(() => { int i = 0; while (!IsDisposed) { if (times > 0 && i >= times) { break; } Receive(); } }); thread.Start(); } public void Receive() { byte[] buffer = new byte[100 * 1024 * 1024]; ManualResetEvent manualResetEvent = new ManualResetEvent(false); try { _SocketClient.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(Received), new object[] { manualResetEvent, buffer }); } catch { manualResetEvent.Dispose(); } manualResetEvent.WaitOne(); manualResetEvent.Dispose(); buffer = null; } private void Received(IAsyncResult asyncResult) { var objs = asyncResult.AsyncState as object[]; var manualResetEvent = objs[0] as ManualResetEvent; var buffer = objs[1] as byte[]; try { _SocketClient.EndReceive(asyncResult); TriggerDataGeted(buffer); } catch (Exception e) { TriggerError(e.Message); } manualResetEvent.Set(); } public void Send(byte[] buffer) { _SocketClient.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(Sended), null); } private void Sended(IAsyncResult asyncResult) { try { _SocketClient.EndSend(asyncResult); } catch (Exception e) { TriggerError(e.Message); } } private void TriggerError(string message) { if (OnError != null) { OnError(this, message); } } private void TriggerConnected() { if (OnConnected != null) { OnConnected(this); } } private void TriggerDataGeted(byte[] buffer) { if (OnDataGeted != null) { OnDataGeted(this, buffer); } } public void Dispose() { IsDisposed = true; try { if (_SocketClient != null) { try { _SocketClient.Disconnect(false); } catch { } _SocketClient.Dispose(); } } catch { } } } }