You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

264 lines
6.4 KiB

3 years ago
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
{
/// <summary>
/// 返回字符串
/// </summary>
public event EventHandler<string> RecData; //定义一个委托类型的事件
/// <summary>
/// 返回type[]
/// </summary>
public event EventHandler<byte[]> OnRecData; //定义一个委托类型的事件
/// <summary>
/// 返回日志
/// </summary>
public event EventHandler<string> OnLog; //定义一个委托类型的事件
private Boolean Listening { get; set; } = false;
private Socket ClientSocket = null;
// private bool Doing = false; //处理数据
public string host;
public int port;
private Dictionary<string, string> PrintList = new Dictionary<string, string>();
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];
/// <summary>
/// 打开客户端,即连接服务器
/// </summary>
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;
}
}
/// <summary>
/// 回调时调用
/// </summary>
/// <param name="ar"></param>
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();
}
}
/// <summary>
/// 发送数据到服务器
/// </summary>
/// <param name="sendStr"></param>
/// <returns></returns>
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;
}
}
/// <summary>
/// Socket 连接状态
/// </summary>
/// <returns></returns>
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);
}
}
}