using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace NNTCPApp.TCP.NNSocket
{
///
/// Class create a connection to listener (server) and has methods to send and
/// receive messages
///
public class ClientSocket : IDisposable
{
public ClientSocket(Socket handler)
{
Handler = handler;
}
private ClientSocket(NetworkItem host)
{
Handler = new Socket(host.NetworkIP.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
LocalEndPoint = new IPEndPoint(host.NetworkIP, host.Port);
}
~ClientSocket()
{
Dispose();
}
public void Dispose()
{
Stop();
}
#region "Methods"
public static ClientSocket Create(NetworkItem host)
{
return new ClientSocket(host);
}
public void Stop()
{
IsConnected = false;
if (Handler?.IsConnected().Result == true)
{
Send($"Disconnected from {Dns.GetHostName()}");
//Allow data to be sent before
System.Threading.Thread.Sleep(1000);
Handler.Shutdown(SocketShutdown.Both);
Handler.Close();
}
Handler?.Dispose();
Handler = null;
}
public async void Connect(Action mesageReceived, Action socketClosed)
{
if(LocalEndPoint != null)
{
Handler.Connect(LocalEndPoint);
Send($"Conected to {Dns.GetHostName()}");
}
await Task.Factory.StartNew(new Action(() =>
{
IsConnected = true;
string message = string.Empty;
while (IsConnected && Handler.IsConnected().Result)
{
if (Handler.ReadMessage(ref message))
{
mesageReceived(message);
message = string.Empty;
}
}
}));
socketClosed?.Invoke(this);
}
public void Send(string message)
{
if (string.IsNullOrEmpty(message) || Handler == null)
return;
// Send the data through the socket.
Handler.Send(Encoding.ASCII.GetBytes(message));
}
#endregion
#region "Properties"
private Socket Handler { get; set; }
private bool IsConnected { get; set; }
private IPEndPoint LocalEndPoint { get; set; }
#endregion
}
}