using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace DIT.Framework.Module._00_Communication
{
///
/// Socket Module을 제어하기 위한 클래스
///
class SocketModule
{
///
/// Client Excpetion Log를 기록하기위한 파라미터.
///
private ILog ExceptionLog = LogManager.GetLogger("ClientException");
///
/// Client Send Log를 기록하기위한 파라미터.
///
private ILog SendLog = LogManager.GetLogger("ClientSend");
///
/// Client Receive Log를 기록하기위한 파라미터.
///
private ILog ReceiveLog = LogManager.GetLogger("ClientReceive");
///
/// 서버와 통신하기 위한 Client Socket
///
public Socket Client { get; private set; }
///
/// 서버와 통신하기 위한 IP
///
public string ip { get; private set; }
///
/// 서버와 통신하기 위한 Port
///
public int port { get; private set;}
///
/// Exception Log 사용유무 확인
///
public bool UseExceptionLog { get; set; }
///
/// Send Log 사용유무 확인
///
public bool UseSendLog { get; set; }
///
/// Receive Log 사용유무 확인
///
public bool UseReceiveLog { get; set; }
///
/// Socket Client 생성자
///
/// 서버에 연결할 IP
/// 서버에 연결할 Port
public SocketModule(string ip, int port)
{
this.ip = ip;
this.port = port;
}
///
/// Exception Log를 기록하기 위한 메서드
///
/// Error Message
private void WriteExceptionLog(string msg)
{
if(UseExceptionLog)
ExceptionLog.Debug(msg);
}
///
/// Send Log를 기록하기 위한 메서드
///
/// Send Message
private void WriteSendLog(string msg)
{
if (UseSendLog)
SendLog.Debug(msg);
}
///
/// Receive Log를 기록하기 위한 메서드
///
/// Receive Message
private void WriteReceiveLog(string msg)
{
if (UseReceiveLog)
ReceiveLog.Debug(msg);
}
///
/// 소켓을 초기화 하고, 서버와 연결하기 위한 메서드
///
///
public bool Connect()
{
try
{
if (Client == null)
Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(ip), port);
//Client.BeginConnect(ipep, new AsyncCallback(ConnectedCallback), Client);
return true;
}
catch (Exception e)
{
WriteExceptionLog(e.Message);
return false;
}
}
///
/// 서버와의 통신을 끊기위한 메서드
///
public void DisConnect()
{
Client.Close();
Client.Dispose();
Client = null;
}
public void Send(string data)
{
try
{
byte[] buffer = Encoding.Default.GetBytes(data);
Client.BeginSend(buffer, 0, buffer.Length, 0, new AsyncCallback(SendCallback), Client);
}
catch (Exception e)
{
WriteExceptionLog(e.Message);
}
}
public void SendCallback(IAsyncResult ar)
{
try
{
Socket sock = (Socket)ar.AsyncState;
int byteSent = sock.EndSend(ar);
}
catch (Exception e)
{
WriteExceptionLog(e.Message);
}
}
}
}