using EC.Utils.Helper;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace EC.Utils.SocketHelper
{
public class SocketClient
{
///
/// 返回字符串
///
public event EventHandler RecData; //定义一个委托类型的事件
///
/// 返回type[]
///
public event EventHandler OnRecData; //定义一个委托类型的事件
///
/// 返回日志
///
public event EventHandler OnLog; //定义一个委托类型的事件
private Boolean Listening { get; set; } = false;
private Socket ClientSocket = null;
// private bool Doing = false; //处理数据
public string host;
public int port;
private Dictionary PrintList = new Dictionary();
private bool SocketconState { get; set; }
public SocketClient(string _host, int _port)
{
host = _host;
port = _port;
}
public bool Start()
{
Stop();
return ConnectServer();
}
private ManualResetEvent allDone = new ManualResetEvent(false);
#region Socket
// byte[] MsgBuffer = new byte[1024];
///
/// 打开客户端,即连接服务器
///
private bool ConnectServer()
{
try
{
Listening = true;
//创建终结点EndPoint
IPAddress ip = IPAddress.Parse(host);
IPEndPoint remotePoint = new IPEndPoint(ip, port); //把ip和端口转化为IPEndPoint的实例
ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//ClientSocket.ReceiveTimeout
ClientSocket.Connect(remotePoint);
//发送信息至服务器
// ClientSocket.Send(Encoding.Unicode.GetBytes("用户: 进入系统!" + "\r\n"));
StateObject state = new StateObject();
state.workSocket = ClientSocket;
ClientSocket.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None,
new AsyncCallback(ReceiveCallback), state);
SocketconState = true;
Log("连接到服务器IP:" + host + " Port:" + port);
return true;
}
catch (ArgumentException e)
{
LogUnit.Error("argumentNullException:" + e.Message);
Stop();
Log("连接到服务器IP:" + host + " Port:" + port + " 失败!");
return false;
}
catch (SocketException e)
{
LogUnit.Error("SocketException:" + e.Message);
Stop();
Log("连接到服务器IP:" + host + " Port:" + port + " 失败!");
return false;
}
catch (Exception e)
{
LogUnit.Error("SocketException:" + e.Message);
Stop();
Log("连接到服务器IP:" + host + " Port:" + port + " 失败!");
return false;
}
}
///
/// 回调时调用
///
///
private void ReceiveCallback(IAsyncResult ar)
{
SocketconState = true;
try
{
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
int read = handler.EndReceive(ar);
// LogUnit.Debug("ReceiveCallback read=" + read);
// LogUnit.Debug("ReceiveCallback state.buffer.Length=" + state.buffer.Length);
if (Listening && read > 0)
{
try
{
byte[] newfuf = ByteHelper.SubArr(state.buffer, 0, read);
OnRecData?.Invoke(this, newfuf);
RecData?.Invoke(this, Encoding.UTF8.GetString(state.buffer, 0, read));
}
catch (Exception ex)
{
LogUnit.Error(this.GetType(), ex);
OnLog?.Invoke(this, ex.Message);
}
//#if DEBUG
// string hexstr = ByteHelper.ByteArrayToHexString(newfuf);
// FileUnit.Log("Rec From PLC Hex =" + hexstr);
//#endif
// string readstring = Encoding.UTF8.GetString(state.buffer, 0, read);
//在此次可以对data进行按需处理
// LogUnit.Debug("clientip: rec: " + readstring);
// byte[] readdata = Protocol.Unpack(state.buffer);
//string readstr = Encoding.UTF8.GetString(readdata);
//在此次可以对data进行按需处理
/// OnRecData(this, readstring);
ClientSocket.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
}
else
{
this.Stop();
}
}
catch (Exception ex)
{
LogUnit.Error(ex.ToString());
this.Stop();
}
}
///
/// 发送数据到服务器
///
///
///
public bool SendToService(string sendStr)
{
try
{
if (ClientSocket == null || ClientSocket.Connected == false)
{
Start();
if (ClientSocket.Connected == false)
{
return false;
}
}
//向服务器发送信息
if (sendStr.Trim() != "HeartBeat") // 过滤心跳
{
LogUnit.Debug("Send:" + sendStr);
}
byte[] bs = Encoding.UTF8.GetBytes(sendStr); //把字符串编码为字节
// bs = Protocol.Packet(bs);
// string hexstr = ByteHelper.ByteArrayToHexString(bs);//记录日志
int x = ClientSocket.Send(bs, bs.Length, 0); //发送信息
SocketconState = true;
return true;
}
catch (Exception ex)
{
string error = "SendToService 不能连接到服务器 " + port + " " + ex.Message;
LogUnit.Error(this.GetType(), error);
Log(error);
return false;
}
}
public bool SendToService(byte[] bs)
{
try
{
if (ClientSocket == null || ClientSocket.Connected == false)
{
Start();
if (ClientSocket.Connected == false)
{
return false;
}
}
int x = ClientSocket.Send(bs, bs.Length, 0); //发送信息
SocketconState = true;
return true;
}
catch (Exception ex)
{
string error = "SendToService 不能连接到服务器 " + port + " " + ex.Message;
LogUnit.Error(this.GetType(), error);
Log(error);
return false;
}
}
#endregion Socket
public void Stop()
{
Listening = false;
SocketconState = false;
if (ClientSocket != null)
{
ClientSocket.Close();
ClientSocket = null;
}
}
///
/// Socket 连接状态
///
///
public bool ConnetionState()
{
if (SocketconState)
{
if (ClientSocket == null || ClientSocket.Connected == false)
{
SocketconState = false;
}
return SocketconState;
}
else
{
return ConnectServer();
}
}
public void Log(string msg)
{
OnLog?.Invoke(this, msg);
}
}
}