客户端
public class TcpClientHelper
{
/// <summary>
/// 是否连接上
/// </summary>
public bool ConnectFlag { get; set; } = false;
/// <summary>
/// 监听的IP
/// </summary>
private string Ip { get; set; }
/// <summary>
/// 监听的端口
/// </summary>
private int Port { get; set; }
/// <summary>
/// 监听每次读取字节数
/// </summary>
private byte[] Buffer { get; set; }
/// <summary>
/// 连接套间字
/// </summary>
private Socket SocketC { get; set; }
/// <summary>
/// 监听线程
/// </summary>
private Thread ListenMsgTh { get; set; }
/// <summary>
/// 监听线程
/// </summary>
private Thread ReConnectTh { get; set; }
/// <summary>
/// 连接事件
/// </summary>
public event Action<string> SocketMessage;
/// <summary>
/// 接收消息
/// </summary>
public event Action<byte[], int> SocketReceive;
/// <summary>
/// 接收消息
/// </summary>
public event Action<byte[], int> SocketSend;
/// <summary>
/// 重连标志
/// </summary>
private bool ReConnnectFlag { get; set; } = false;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="ip">连接服务器的IP</param>
/// <param name="port">连接服务器的端口</param>
public TcpClientHelper(string ip, int port, int bufferLength = 1024 * 1024)
{
Ip = ip;
Port = port;
Buffer = new byte[bufferLength];
}
/// <summary>
/// 初始化
/// </summary>
/// <param name="count">重连次数</param>
/// <param name="delayTime">重连时间</param>
public bool Init()
{
//连接
if (!Connect())
return false;
//监听
if (SocketC.Connected)
{
ListenMsgTh = new Thread(receive);
ListenMsgTh.IsBackground = true;
ListenMsgTh.Start();
}
return true;
}
/// <summary>
/// 连接
/// </summary>
/// <returns></returns>
private bool Connect()
{
try
{
//1.0 实例化套接字(IP4寻址地址,流式传输,TCP协议)
SocketC = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//2.0 创建IP对象
IPAddress address = IPAddress.Parse(Ip);
//3.0 创建网络端口包括ip和端口
IPEndPoint endPoint = new IPEndPoint(address, Port);
//4.0 建立连接
SocketC.Connect(endPoint);
//5.0 连接上服务端
return ConnectFlag = true;
}
catch { }
return ConnectFlag = false;
}
/// <summary>
/// 重新连接
/// </summary>
public void ReConnect(SocketException ex)
{
if (!ReConnnectFlag)
{
SocketMessage?.Invoke("socket连接出错" + ex.Message + ex.StackTrace);
//释放资源
Close();
//重连
ReConnectTh = new Thread(delegate ()
{
try
{
//循环重连
for (; ; )
{
if (Connect())
{
break;
}
Thread.Sleep(10000);
}
SocketMessage?.Invoke("重连成功");
//重新开启监听
if (SocketC.Connected)
{
ListenMsgTh = new Thread(receive)
{
IsBackground = true
};
ListenMsgTh.Start();
}
//置位信号
ReConnnectFlag = false;
}
catch (ThreadInterruptedException)
{
ReConnnectFlag = false;
}
})
{
IsBackground = true
};
ReConnectTh.Start();
}
else
{
return;
}
}
/// <summary>
/// 发送数据
/// </summary>
/// <param name="buffer">字节数组数据</param>
public void sendMessage(byte[] buffer)
{
try
{
if (SocketC.Connected)
{
SocketC.Send(buffer);
}
SocketSend?.Invoke(buffer, buffer.Length);
}
catch (SocketException ex)
{
ReConnect(ex);
}
}
/// <summary>
/// 接收数据
/// </summary>
public void receive()
{
try
{
for (; ; )
{
//接收的字节数,当客户端下线时,receiveNumber=0
int receiveNumber = SocketC.Receive(Buffer);
//判断服务端是否下线,防止服务端下线时,客户端一直接收空消息
if (receiveNumber == 0)
{
throw new SocketException();
}
//接收事件
SocketReceive?.Invoke(Buffer, receiveNumber);
}
}
catch (SocketException ex)
{
ReConnect(ex);
}
catch (ThreadInterruptedException)
{ }
}
/// <summary>
/// 释放所有套间字
/// </summary>
public void Close()
{
ReConnnectFlag = true;
ConnectFlag = false;
//中断线程
if (ListenMsgTh != null && ListenMsgTh.IsAlive)
{
ListenMsgTh.Interrupt();
}
if (ReConnectTh != null && ReConnectTh.IsAlive)
{
ReConnectTh.Interrupt();
}
//关闭连接
if (SocketC.Connected)
{
SocketC.Shutdown(SocketShutdown.Both);
SocketC.Close();
}
}
/// <summary>
/// 析构函数
/// </summary>
~TcpClientHelper()
{
Close();
}
}
服务端
/// <summary>
/// TCP服务端
/// </summary>
public class TcpServerHelper : IDisposable
{
/// <summary>
/// 监听套间字
/// </summary>
private Socket SocketS { get; set; }
/// <summary>
/// 连接池数列
/// </summary>
private List<Socket> SocketClients { get; set; }
/// <summary>
/// 连接数
/// </summary>
public int ConnectCount { get { return SocketClients.Count; } }
/// <summary>
/// 是否监听
/// </summary>
public bool isListening { get { return SocketS.IsBound; } }
/// <summary>
/// 监听的IP
/// </summary>
private string Ip { get; set; }
/// <summary>
/// 监听的端口
/// </summary>
private int Port { get; set; }
/// <summary>
/// 监听每次读取字节数
/// </summary>
private byte[] Buffer { get; set; }
/// <summary>
/// 最大连接数
/// </summary>
private int Count { get; set; }
/// <summary>
/// 接收消息
/// </summary>
public event Action<byte[], int, EndPoint> SocketReceive;
/// <summary>
/// 报错事件
/// </summary>
public event Action<string, Exception, EndPoint> SocketMessage;
/// <summary>
/// 连接事件
/// </summary>
public event Action<bool, EndPoint> ConnectEndPoints;
/// <summary>
/// /// <summary>
/// 构造函数
/// </summary>
/// <param name="ip">监听的IP</param>
/// <param name="port">监听的端口</param>
/// <param name="bufferLength">监听每次读取字节数,默认1MB = 1024 * 1024B</param>
public TcpServerHelper(string ip, int port, int bufferLength = 1024 * 1024, int count = int.MaxValue)
{
Ip = ip;
Port = port;
Buffer = new byte[bufferLength];
SocketClients = new List<Socket>();
Count = count;
}
/// <summary>
/// 开始监听
/// </summary>
/// <returns></returns>
public async Task Listen()
{
try
{
//1.0 实例化套接字(IP4寻找协议,流式协议,TCP协议)
SocketS = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//2.0 创建IP对象
IPAddress address = IPAddress.Parse(Ip);
//3.0 创建网络端口,包括ip和端口
IPEndPoint endPoint = new IPEndPoint(address, Port);
//4.0 绑定套接字
SocketS.Bind(endPoint);
//5.0 设置最大连接数
SocketS.Listen(Count);
//6.0 循环遍历连接
await Task.Run(() =>
{
for (; ; )
{
try
{
//接收客户端连接
Socket SocketClient = SocketS.Accept();
//加入连接池数列
SocketClients.Add(SocketClient);
//连接事件
SocketMessage?.Invoke($"{SocketClient.RemoteEndPoint}接入", null, SocketClient.RemoteEndPoint);
ConnectEndPoints?.Invoke(true, SocketClient.RemoteEndPoint);
//开始监听
Thread thread = new Thread(Receive);
thread.Start(SocketClient);
}
catch (SocketException ex)
{
SocketMessage?.Invoke("服务监听出错", ex, null);
}
catch (Exception ex)
{
LogHelper.GetInstance().WriteLogEx(ex);
}
}
});
}
catch (Exception ex)
{
SocketMessage?.Invoke("服务监听出错", ex, null);
}
}
/// <summary>
/// 发送数据
/// </summary>
/// <param name="buffer"></param>
/// <returns></returns>
public void Send(byte[] buffer)
{
for (int index = SocketClients.Count - 1; index >= 0; index--)
{
try
{
SocketClients[index].Send(buffer);
}
catch (SocketException ex)
{
CloseConnect(SocketClients[index], ex);
}
}
}
/// <summary>
/// 接收消息
/// </summary>
/// <param name="socket">来自客户端的socket</param>
private void Receive(object SocketClient)
{
Socket socketClient = (Socket)SocketClient;
try
{
for (; ; )
{
//接收的字节数,当客户端下线时,receiveNumber=0
int receiveNumber = socketClient.Receive(Buffer);
//判断客户端是否下线,防止客户端下线时,服务端一直接收空消息
if (receiveNumber == 0)
{
throw new SocketException();
}
//接收成功事件
SocketReceive(Buffer, receiveNumber, socketClient.RemoteEndPoint);
}
}
catch (SocketException ex)
{
CloseConnect(socketClient, ex);
}
catch (Exception)
{
}
}
/// <summary>
/// 断开连接
/// </summary>
/// <param name="socket"></param>
/// <param name="ex"></param>
private void CloseConnect(Socket socket, SocketException ex)
{
SocketMessage?.Invoke($"{socket.RemoteEndPoint}断开连接", ex, socket.RemoteEndPoint);
ConnectEndPoints?.Invoke(false, socket.RemoteEndPoint);
socket.Close();
SocketClients.Remove(socket);
}
/// <summary>
/// 释放所有套间字
/// </summary>
public void Dispose()
{
try
{
SocketS.Close();
foreach (Socket socket in SocketClients)
{
socket.Close();
}
}
catch{ }
}
/// <summary>
/// 析构函数
/// </summary>
~TcpServerHelper()
{
Dispose();
}
}