HaoYueNet/NetLib/HaoYueNet.ServerNetwork/NetWork/TcpSaeaServer.cs

723 lines
27 KiB
C#
Raw Permalink Normal View History

//using HunterProtobufCore;
2024-06-27 15:49:56 +08:00
using System.Buffers;
2021-12-10 23:38:40 +08:00
using System.Net;
using System.Net.Sockets;
using static HaoYueNet.ServerNetwork.BaseData;
2021-12-10 23:38:40 +08:00
namespace HaoYueNet.ServerNetwork
{
2023-07-06 14:47:20 +08:00
public class TcpSaeaServer
2021-12-10 23:38:40 +08:00
{
2024-01-15 11:28:29 +08:00
#region
protected int MaxRevIndexNum = 50;//响应倒计时计数最大值
protected int MaxSendIndexNum = 3;//发送倒计时计数最大值
protected static int TimerInterval = 3000;//计时器间隔
protected System.Timers.Timer _heartTimer;//心跳包计数器
2021-12-10 23:38:40 +08:00
public int m_maxConnectNum; //最大连接数
public int m_revBufferSize; //最大接收字节数
2023-07-06 14:47:20 +08:00
protected BufferManager m_bufferManager;
protected const int opsToAlloc = 2;
2021-12-10 23:38:40 +08:00
Socket listenSocket; //监听Socket
2023-07-06 14:47:20 +08:00
protected SocketEventPool m_Receivepool;
protected SocketEventPool m_Sendpool;
protected TokenMsgPool msg_pool;
protected int m_clientCount; //连接的客户端数量
protected Semaphore m_maxNumberAcceptedClients;//信号量
protected Dictionary<Socket, AsyncUserToken> _DictSocketAsyncUserToken = new Dictionary<Socket, AsyncUserToken>();
2024-01-15 11:28:29 +08:00
List<AsyncUserToken> m_clients; //客户端列表
public List<AsyncUserToken> ClientList { private set { m_clients = value; } get { return m_clients; } } //获取客户端列表
#endregion
2023-06-29 19:20:14 +08:00
2021-12-10 23:38:40 +08:00
#region
/// <summary>
/// 客户端连接数量变化时触发
/// </summary>
/// <param name="num">当前增加客户的个数(用户退出时为负数,增加时为正数,一般为1)</param>
/// <param name="token">增加用户的信息</param>
2023-07-06 14:47:20 +08:00
public delegate void OnClientNumberChangeHandler(int num, AsyncUserToken token);
2021-12-10 23:38:40 +08:00
/// <summary>
/// 接收到客户端的数据
/// </summary>
/// <param name="token">客户端</param>
/// <param name="buff">客户端数据</param>
2023-07-06 14:47:20 +08:00
public delegate void OnReceiveDataHandler(AsyncUserToken sk, int CMDID, byte[] data);
/// <summary>
/// 断开连接
/// </summary>
/// <param name="sk"></param>
public delegate void OnDisconnectHandler(AsyncUserToken sk);
/// <summary>
/// 日志
/// </summary>
/// <param name="sk"></param>
public delegate void OnNetLogHandler(string msg);
2021-12-10 23:38:40 +08:00
#endregion
#region
/// <summary>
/// 客户端连接数量变化事件
2023-07-06 14:47:20 +08:00
/// </summary>
public event OnClientNumberChangeHandler OnClientNumberChange;
2021-12-10 23:38:40 +08:00
/// <summary>
/// 接收到客户端的数据事件
2023-07-06 14:47:20 +08:00
/// </summary>
public event OnReceiveDataHandler OnReceive;
/// <summary>
/// 接收到客户端的断开连接
/// </summary>
public event OnDisconnectHandler OnDisconnected;
/// <summary>
/// 网络库内部输出
/// </summary>
public event OnNetLogHandler OnNetLog;
2021-12-10 23:38:40 +08:00
#endregion
2024-01-15 11:28:29 +08:00
/// <summary>
/// 构造函数
/// </summary>
2021-12-10 23:38:40 +08:00
/// <param name="numConnections">最大连接数</param>
/// <param name="receiveBufferSize">缓存区大小</param>
2023-07-06 14:47:20 +08:00
public TcpSaeaServer(int numConnections, int receiveBufferSize)
2021-12-10 23:38:40 +08:00
{
m_clientCount = 0;
m_maxConnectNum = numConnections;
m_revBufferSize = receiveBufferSize;
// allocate buffers such that the maximum number of sockets can have one outstanding read and
2023-06-29 19:20:14 +08:00
//write posted to the socket simultaneously
2021-12-10 23:38:40 +08:00
m_bufferManager = new BufferManager(receiveBufferSize * numConnections * opsToAlloc, receiveBufferSize);
2023-06-29 19:20:14 +08:00
m_Receivepool = new SocketEventPool(numConnections);
2021-12-10 23:38:40 +08:00
m_Sendpool = new SocketEventPool(numConnections);
msg_pool = new TokenMsgPool(numConnections);
m_maxNumberAcceptedClients = new Semaphore(numConnections, numConnections);
}
2024-01-15 11:28:29 +08:00
#region Client操作
2021-12-10 23:38:40 +08:00
/// <summary>
/// 初始化
/// </summary>
public void Init()
{
// Allocates one large byte buffer which all I/O operations use a piece of. This gaurds
// against memory fragmentation
m_bufferManager.InitBuffer();
m_clients = new List<AsyncUserToken>();
// preallocate pool of SocketAsyncEventArgs objects
SocketAsyncEventArgs readWriteEventArg;
for (int i = 0; i < m_maxConnectNum; i++)
{
readWriteEventArg = new SocketAsyncEventArgs();
readWriteEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed);
readWriteEventArg.UserToken = new AsyncUserToken();
// assign a byte buffer from the buffer pool to the SocketAsyncEventArg object
m_bufferManager.SetBuffer(readWriteEventArg);
// add SocketAsyncEventArg to the pool
2023-06-29 19:20:14 +08:00
m_Receivepool.Push(readWriteEventArg);
2021-12-10 23:38:40 +08:00
}
for (int i = 0; i < m_maxConnectNum; i++)
{
readWriteEventArg = new SocketAsyncEventArgs();
2023-06-29 19:20:14 +08:00
readWriteEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed);
2021-12-10 23:38:40 +08:00
readWriteEventArg.UserToken = new AsyncUserToken();
2023-06-29 19:20:14 +08:00
//发送是否需要如此设置 TODO
2021-12-10 23:38:40 +08:00
m_bufferManager.SetBuffer(readWriteEventArg);
2023-06-29 19:20:14 +08:00
2021-12-10 23:38:40 +08:00
m_Sendpool.Push(readWriteEventArg);
}
2023-07-06 14:47:20 +08:00
OutNetLog("初始化完毕");
2021-12-10 23:38:40 +08:00
}
2023-06-02 18:24:54 +08:00
/// <summary>
/// 启动服务
/// </summary>
/// <param name="localEndPoint"></param>
/// <param name="bReuseAddress">是否端口重用</param>
/// <returns></returns>
2023-07-06 14:47:20 +08:00
public bool Start(IPEndPoint localEndPoint, bool bReuseAddress = false)
2021-12-10 23:38:40 +08:00
{
try
{
2023-06-29 19:20:14 +08:00
ClearUserToken();
2021-12-10 23:38:40 +08:00
listenSocket = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
2023-06-02 18:24:54 +08:00
if (bReuseAddress)
{
listenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
}
2021-12-10 23:38:40 +08:00
listenSocket.Bind(localEndPoint);
// start the server with a listen backlog of 100 connections
listenSocket.Listen(m_maxConnectNum);
// post accepts on the listening socket
StartAccept(null);
2021-12-27 23:52:27 +08:00
2023-12-14 18:15:04 +08:00
OutNetLog("监听:" + listenSocket.LocalEndPoint.ToString());
2023-07-06 14:47:20 +08:00
2021-12-10 23:38:40 +08:00
_heartTimer = new System.Timers.Timer();
_heartTimer.Interval = TimerInterval;
_heartTimer.Elapsed += CheckUpdatetimer_Elapsed;
_heartTimer.AutoReset = true;
_heartTimer.Enabled = true;
2023-07-06 14:47:20 +08:00
OutNetLog("开启定时心跳包");
2021-12-10 23:38:40 +08:00
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// 停止服务
/// </summary>
public void Stop()
{
foreach (AsyncUserToken token in m_clients)
{
try
{
token.Socket.Shutdown(SocketShutdown.Both);
}
catch (Exception) { }
}
try
{
listenSocket.Shutdown(SocketShutdown.Both);
}
catch (Exception) { }
listenSocket.Close();
int c_count = m_clients.Count;
2023-06-29 19:20:14 +08:00
ClearUserToken();
2021-12-10 23:38:40 +08:00
2023-07-06 14:47:20 +08:00
if (OnClientNumberChange != null)
OnClientNumberChange(-c_count, null);
2021-12-10 23:38:40 +08:00
}
public void CloseClient(AsyncUserToken token)
{
2024-01-15 11:28:29 +08:00
try {token.Socket.Shutdown(SocketShutdown.Both);}
2021-12-10 23:38:40 +08:00
catch (Exception) { }
}
2024-01-15 11:28:29 +08:00
/// <summary>
/// 关闭客户端连接
/// </summary>
/// <param name="e"></param>
void CloseClientSocket(SocketAsyncEventArgs e)
2023-07-06 14:47:20 +08:00
{
AsyncUserToken token = e.UserToken as AsyncUserToken;
2024-01-15 11:28:29 +08:00
CloseReady(token);
// 释放SocketAsyncEventArg以便其他客户端可以重用它们
ReleaseSocketAsyncEventArgs(e);
}
void CloseReady(AsyncUserToken token)
{
2023-07-06 14:47:20 +08:00
OnDisconnected?.Invoke(token);
RemoveUserToken(token);
2024-01-15 11:28:29 +08:00
//如果有事件,则调用事件,发送客户端数量变化通知
2023-07-06 14:47:20 +08:00
OnClientNumberChange?.Invoke(-1, token);
2024-01-15 11:28:29 +08:00
// 关闭与客户端关联的套接字
try { token.Socket.Shutdown(SocketShutdown.Send); } catch (Exception) { }
2023-07-06 14:47:20 +08:00
token.Socket.Close();
2024-01-15 11:28:29 +08:00
// 递减计数器以跟踪连接到服务器的客户端总数
2023-07-06 14:47:20 +08:00
Interlocked.Decrement(ref m_clientCount);
m_maxNumberAcceptedClients.Release();
}
#endregion
#region Token管理
2024-01-15 11:28:29 +08:00
public AsyncUserToken GetAsyncUserTokenForSocket(Socket sk)
{
2024-08-23 16:18:37 +08:00
AsyncUserToken result;
if (_DictSocketAsyncUserToken.TryGetValue(sk, out result))
return result;
return null;
//return _DictSocketAsyncUserToken.ContainsKey(sk) ? _DictSocketAsyncUserToken[sk] : null;
2024-01-15 11:28:29 +08:00
}
2023-07-06 14:47:20 +08:00
void AddUserToken(AsyncUserToken userToken)
{
lock (_DictSocketAsyncUserToken)
{
m_clients.Add(userToken);
_DictSocketAsyncUserToken.Add(userToken.Socket, userToken);
}
}
void RemoveUserToken(AsyncUserToken userToken)
{
lock (_DictSocketAsyncUserToken)
{
m_clients.Remove(userToken);
_DictSocketAsyncUserToken.Remove(userToken.Socket);
}
}
void ClearUserToken()
{
lock (_DictSocketAsyncUserToken)
{
m_clients.Clear();
_DictSocketAsyncUserToken.Clear();
}
}
2024-01-15 11:28:29 +08:00
/// <summary>
/// 回收SocketAsyncEventArgs
/// </summary>
/// <param name="saea"></param>
/// <exception cref="ArgumentException"></exception>
void ReleaseSocketAsyncEventArgs(SocketAsyncEventArgs saea)
2023-07-06 14:47:20 +08:00
{
2024-01-15 11:28:29 +08:00
//saea.UserToken = null;//TODO
//saea.SetBuffer(null, 0, 0);
//saea.Dispose();
//↑ 这里不要自作主张去清东西,否则回收回去不可用
switch (saea.LastOperation)
{
case SocketAsyncOperation.Receive:
m_Receivepool.Push(saea);
break;
case SocketAsyncOperation.Send:
m_Sendpool.Push(saea);
break;
default:
throw new ArgumentException("ReleaseSocketAsyncEventArgs > The last operation completed on the socket was not a receive or send");
}
2023-07-06 14:47:20 +08:00
}
#endregion
2021-12-10 23:38:40 +08:00
2024-01-15 11:28:29 +08:00
#region IOCP循环
/// <summary>
/// 开始接受客户端的连接请求的操作
/// </summary>
/// <param name="acceptEventArg">在服务器的侦听套接字上发出接受操作时要使用的上下文对象</param>
2021-12-10 23:38:40 +08:00
public void StartAccept(SocketAsyncEventArgs acceptEventArg)
{
if (acceptEventArg == null)
{
acceptEventArg = new SocketAsyncEventArgs();
acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(AcceptEventArg_Completed);
}
else
{
// socket must be cleared since the context object is being reused
acceptEventArg.AcceptSocket = null;
}
m_maxNumberAcceptedClients.WaitOne();
if (!listenSocket.AcceptAsync(acceptEventArg))
{
ProcessAccept(acceptEventArg);
}
}
2024-01-15 11:28:29 +08:00
/// <summary>
/// 此方法是与Socket关联的回调方法。AcceptAsync操作并在接受操作完成时调用
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
2021-12-10 23:38:40 +08:00
void AcceptEventArg_Completed(object sender, SocketAsyncEventArgs e)
{
ProcessAccept(e);
}
private void ProcessAccept(SocketAsyncEventArgs e)
{
try
{
Interlocked.Increment(ref m_clientCount);
2023-12-14 18:15:04 +08:00
2024-01-22 13:04:27 +08:00
//确保监听结束时,有连接才抛给数据接收
if (e.AcceptSocket.RemoteEndPoint != null)
{
// Get the socket for the accepted client connection and put it into the
//ReadEventArg object user token
SocketAsyncEventArgs readEventArgs = m_Receivepool.Pop();
//TODO readEventArgs.UserToken这里的 UserToken 有可能是空
AsyncUserToken userToken;
if (readEventArgs.UserToken == null)
readEventArgs.UserToken = new AsyncUserToken();
2021-12-10 23:38:40 +08:00
2024-01-22 13:04:27 +08:00
userToken = (AsyncUserToken)readEventArgs.UserToken;
userToken.Socket = e.AcceptSocket;
userToken.ConnectTime = DateTime.Now;
userToken.Remote = e.AcceptSocket.RemoteEndPoint;
userToken.IPAddress = ((IPEndPoint)(e.AcceptSocket.RemoteEndPoint)).Address;
2021-12-10 23:38:40 +08:00
2024-01-22 13:04:27 +08:00
userToken.RevIndex = MaxRevIndexNum;
userToken.SendIndex = MaxSendIndexNum;
2021-12-10 23:38:40 +08:00
2024-01-22 13:04:27 +08:00
AddUserToken(userToken);
OnClientNumberChange?.Invoke(1, userToken);
if (!e.AcceptSocket.ReceiveAsync(readEventArgs))
{
ProcessReceive(readEventArgs);
}
2021-12-10 23:38:40 +08:00
}
}
catch (Exception me)
{
//RuncomLib.Log.LogUtils.Info(me.Message + "\r\n" + me.StackTrace);
}
// Accept the next connection request
if (e.SocketError == SocketError.OperationAborted) return;
StartAccept(e);
}
2023-07-06 14:47:20 +08:00
#endregion
2021-12-27 23:52:27 +08:00
2024-01-15 11:28:29 +08:00
#region IOCP循环
/// <summary>当异步接收操作完成时,会调用此方法。
/// 如果远程主机关闭了连接,则套接字关闭。
/// 如果接收到数据,则将数据回显到客户端。
/// </summary>
/// <param name="e"></param>
2021-12-10 23:38:40 +08:00
private void ProcessReceive(SocketAsyncEventArgs e)
{
try
{
AsyncUserToken token = (AsyncUserToken)e.UserToken;
if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
{
2024-04-07 17:00:19 +08:00
lock(token.memoryStream)
2021-12-10 23:38:40 +08:00
{
2024-04-07 17:00:19 +08:00
token.memoryStream.Write(e.Buffer, e.Offset, e.BytesTransferred);
do
2021-12-10 23:38:40 +08:00
{
2024-06-27 15:49:56 +08:00
if (token.memoryStream.Length < 4) break;//包头不完整,继续接收
2024-04-07 17:00:19 +08:00
long FristBeginPos = token.memoryStream.Position;
2024-06-27 15:49:56 +08:00
//从Byte池申请
byte[] lenBytes = ArrayPool<byte>.Shared.Rent(4);
token.memoryStream.Seek(0, SeekOrigin.Begin);
2024-04-07 17:00:19 +08:00
token.memoryStream.Read(lenBytes, 0, 4);
int packageLen = BitConverter.ToInt32(lenBytes, 0) - 4;
2024-06-27 15:49:56 +08:00
//归还byte[]
ArrayPool<byte>.Shared.Return(lenBytes);
if (packageLen > token.memoryStream.Length - 4)
{
2024-04-07 17:00:19 +08:00
token.memoryStream.Seek(FristBeginPos, SeekOrigin.Begin);
2024-06-27 15:49:56 +08:00
break;//长度不够时,退出循环,让程序继续接收
}
2024-06-27 15:49:56 +08:00
//申请byte池 一定要记得回收!!
byte[] rev_fromArrayPool = ArrayPool<byte>.Shared.Rent(packageLen);
2024-06-27 15:49:56 +08:00
token.memoryStream.Seek(4, SeekOrigin.Begin);
token.memoryStream.Read(rev_fromArrayPool, 0, packageLen);
2024-04-07 17:00:19 +08:00
token.memoryStream.Seek(FristBeginPos, SeekOrigin.Begin);
//从数据池中移除这组数据
lock (token.memoryStream)
{
int numberOfBytesToRemove = packageLen + 4;
byte[] buf = token.memoryStream.GetBuffer();
Buffer.BlockCopy(buf, numberOfBytesToRemove, buf, 0, (int)token.memoryStream.Length - numberOfBytesToRemove);
token.memoryStream.SetLength(token.memoryStream.Length - numberOfBytesToRemove);
}
2024-06-27 15:49:56 +08:00
//用Span内存切片因为来自ArrayPool的byte长度可能大于本身申请的长度
Span<byte> rev_span = rev_fromArrayPool;
rev_span = rev_span.Slice(0, packageLen);
DataCallBackReady(token, rev_span);
2024-06-27 15:49:56 +08:00
//回收这里依赖DataCallBackReady中有一次数据拷贝这个后续还要进一步精进性能优化否则不能在这里回收否则影响业务层
ArrayPool<byte>.Shared.Return(rev_fromArrayPool);
2024-04-07 17:00:19 +08:00
} while (token.memoryStream.Length > 4);
}
2021-12-10 23:38:40 +08:00
2024-06-27 15:49:56 +08:00
//如果返回为False则代表此刻已经完成不必等待完成端口回调则直接调用ProcessReceive
2021-12-10 23:38:40 +08:00
if (!token.Socket.ReceiveAsync(e))
this.ProcessReceive(e);
}
else
{
2024-06-27 15:49:56 +08:00
//清理数据
2024-05-20 17:36:47 +08:00
token.memoryStream.SetLength(0);
token.memoryStream.Seek(0, SeekOrigin.Begin);
2021-12-10 23:38:40 +08:00
CloseClientSocket(e);
}
}
catch (Exception xe)
{
//RuncomLib.Log.LogUtils.Info(xe.Message + "\r\n" + xe.StackTrace);
}
}
private void ProcessSend(SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success)
{
2023-06-29 19:20:14 +08:00
//TODO
2021-12-10 23:38:40 +08:00
}
else
{
CloseClientSocket(e);
2023-06-29 19:20:14 +08:00
return;
2021-12-10 23:38:40 +08:00
}
2023-06-29 19:20:14 +08:00
ReleaseSocketAsyncEventArgs(e);
2021-12-10 23:38:40 +08:00
SendForMsgPool();
}
2023-07-06 14:47:20 +08:00
void IO_Completed(object sender, SocketAsyncEventArgs e)
2021-12-10 23:38:40 +08:00
{
2023-07-06 14:47:20 +08:00
switch (e.LastOperation)
2021-12-10 23:38:40 +08:00
{
2023-07-06 14:47:20 +08:00
case SocketAsyncOperation.Receive:
ProcessReceive(e);
break;
case SocketAsyncOperation.Send:
ProcessSend(e);
break;
default:
throw new ArgumentException("The last operation completed on the socket was not a receive or send");
2021-12-10 23:38:40 +08:00
}
2023-06-29 19:20:14 +08:00
}
2023-07-06 14:47:20 +08:00
#endregion
2023-06-29 19:20:14 +08:00
2024-01-15 11:28:29 +08:00
#region
int sendrun = 0;
2023-07-06 14:47:20 +08:00
/// <summary>
2024-01-15 11:28:29 +08:00
/// 对外暴露的发送消息
2023-07-06 14:47:20 +08:00
/// </summary>
2024-01-15 11:28:29 +08:00
/// <param name="CMDID"></param>
/// <param name="data">序列化之后的数据</param>
public void SendToSocket(Socket sk, int CMDID, int ERRCODE, byte[] data)
2023-06-29 19:20:14 +08:00
{
2024-01-15 11:28:29 +08:00
AsyncUserToken token = GetAsyncUserTokenForSocket(sk);
/*HunterNet_S2C _s2cdata = new HunterNet_S2C();
_s2cdata.HunterNetCoreCmdID = CMDID;
_s2cdata.HunterNetCoreData = ByteString.CopyFrom(data);
_s2cdata.HunterNetCoreERRORCode = ERRCODE;
byte[] _finaldata = Serizlize(_s2cdata);*/
2023-12-18 14:37:58 +08:00
2024-01-15 11:28:29 +08:00
//byte[] _finaldata = HunterNet_S2C.CreatePkgData((ushort)CMDID, (ushort)ERRCODE, data);
2023-12-18 14:37:58 +08:00
2024-01-15 11:28:29 +08:00
SendWithIndex(token, (ushort)CMDID, (ushort)ERRCODE, data);
2021-12-10 23:38:40 +08:00
}
2024-01-15 11:28:29 +08:00
void SendForMsgPool()
2021-12-10 23:38:40 +08:00
{
//if (flag_SendForMsgPool) return;
try
{
if (sendrun < msg_pool.Count || msg_pool.Count < 1)
return;
sendrun++;
while (msg_pool.Count > 0)
{
try
{
TokenWithMsg msg = msg_pool.Dequeue();
2023-07-06 14:47:20 +08:00
//OutNetLog("从信息池取出发送");
2024-01-08 16:19:09 +08:00
//是心跳包
if (msg.bHeartbeat)
{
SendHeartbeatMessage(msg.token);
}
else
{
2024-01-15 11:28:29 +08:00
SendMessage(msg.token, msg.CMDID, msg.Error, msg.data);
2024-01-08 16:19:09 +08:00
}
2021-12-10 23:38:40 +08:00
msg = null;
}
catch
{
2023-07-06 14:47:20 +08:00
OutNetLog("==============================================>");
2021-12-10 23:38:40 +08:00
}
}
sendrun--;
2023-07-06 14:47:20 +08:00
OutNetLog("!!!!!!!!!!!!!!!!!!!!!!!!!!");
2021-12-10 23:38:40 +08:00
}
2021-12-27 23:52:27 +08:00
catch (Exception ex)
2021-12-10 23:38:40 +08:00
{
2023-07-06 14:47:20 +08:00
OutNetLog(ex.ToString());
2021-12-10 23:38:40 +08:00
}
2021-12-27 23:52:27 +08:00
2021-12-10 23:38:40 +08:00
}
2024-01-15 11:28:29 +08:00
/// <summary>
/// 发送心跳包
/// </summary>
/// <param name="token"></param>
void SendHeartbeatMessage(AsyncUserToken token)
2021-12-10 23:38:40 +08:00
{
if (token == null || token.Socket == null || !token.Socket.Connected)
return;
try
{
if (m_Sendpool.Count > 0)
{
SocketAsyncEventArgs myreadEventArgs = m_Sendpool.Pop();
myreadEventArgs.UserToken = token;
myreadEventArgs.AcceptSocket = token.Socket;
2024-01-15 11:28:29 +08:00
//直接写入SocketAsyncEventArgs的Buff
HunterNet_Heartbeat.SetDataToSocketAsyncEventArgs(myreadEventArgs);
2021-12-27 23:52:27 +08:00
2023-06-29 19:20:14 +08:00
//若不需要等待
if (!token.Socket.SendAsync(myreadEventArgs))
{
m_Sendpool.Push(myreadEventArgs);
}
2021-12-10 23:38:40 +08:00
return;
}
else
{
2023-06-29 19:20:14 +08:00
//先压入队列等待m_Sendpool回收
2024-01-15 11:28:29 +08:00
msg_pool.Enqueue(new TokenWithMsg() { token = token, bHeartbeat = true });
2023-07-06 14:47:20 +08:00
//OutNetLog("压入消息发送队列MSG_Pool");
2021-12-10 23:38:40 +08:00
return;
}
}
catch (Exception e)
{
2023-07-06 14:47:20 +08:00
OutNetLog(e.ToString());
2021-12-10 23:38:40 +08:00
}
}
2024-01-08 16:19:09 +08:00
2024-01-15 11:28:29 +08:00
/// <summary>
/// 发送数据并计数
/// </summary>
/// <param name="data"></param>
void SendWithIndex(AsyncUserToken token, UInt16 CmdID, UInt16 ERRCODE, byte[] data)
2024-01-08 16:19:09 +08:00
{
try
{
2024-01-15 11:28:29 +08:00
//发送数据
SendMessage(token, CmdID, ERRCODE, data);
token.SendIndex = MaxSendIndexNum;
2024-01-08 16:19:09 +08:00
}
2024-01-15 11:28:29 +08:00
catch
2024-01-08 16:19:09 +08:00
{
2024-01-15 11:28:29 +08:00
CloseReady(token);
2024-01-08 16:19:09 +08:00
}
}
2024-01-15 11:28:29 +08:00
void SendMessage(AsyncUserToken token, UInt16 CmdID, UInt16 Error, byte[] data)
2024-01-08 16:19:09 +08:00
{
if (token == null || token.Socket == null || !token.Socket.Connected)
return;
try
{
if (m_Sendpool.Count > 0)
{
SocketAsyncEventArgs myreadEventArgs = m_Sendpool.Pop();
myreadEventArgs.UserToken = token;
myreadEventArgs.AcceptSocket = token.Socket;
2024-01-15 11:28:29 +08:00
//myreadEventArgs.SetBuffer(message, 0, message.Length); //将数据放置进去.
//更换为CMDID和Data直接写入SocketAsyncEventArgs的Buff
HunterNet_S2C.SetDataToSocketAsyncEventArgs(myreadEventArgs, CmdID, Error, data);
2024-01-08 16:19:09 +08:00
//若不需要等待
if (!token.Socket.SendAsync(myreadEventArgs))
{
m_Sendpool.Push(myreadEventArgs);
}
return;
}
else
{
//先压入队列等待m_Sendpool回收
2024-01-15 11:28:29 +08:00
msg_pool.Enqueue(new TokenWithMsg() { token = token, CMDID = CmdID, Error = Error, data = data });
2024-01-08 16:19:09 +08:00
//OutNetLog("压入消息发送队列MSG_Pool");
return;
}
}
catch (Exception e)
{
OutNetLog(e.ToString());
}
}
2024-01-15 11:28:29 +08:00
#endregion
2021-12-10 23:38:40 +08:00
2024-01-15 11:28:29 +08:00
#region
2024-06-27 15:49:56 +08:00
private void DataCallBackReady(AsyncUserToken sk, Span<byte> data)
2021-12-10 23:38:40 +08:00
{
//增加接收计数
sk.RevIndex = MaxRevIndexNum;
if (data.Length == 1 && data[0] == 0x00)//心跳包
{
2023-07-06 14:47:20 +08:00
//OutNetLog("收到心跳包");
2021-12-10 23:38:40 +08:00
//无处理
}
else
{
try
{
2023-07-06 14:47:20 +08:00
//将数据包交给后台处理,这里你也可以新开个线程来处理.加快速度.
/*
HunterNet_C2S _s2c = DeSerizlize<HunterNet_C2S>(data);
2023-07-06 14:47:20 +08:00
OnReceive?.Invoke(sk, (int)_s2c.HunterNetCoreCmdID, _s2c.HunterNetCoreData.ToArray());
//DataCallBack(sk, (int)_s2c.HunterNetCoreCmdID, _s2c.HunterNetCoreData.ToArray());
*/
HunterNet_C2S.AnalysisPkgData(data, out ushort CmdID, out byte[] resultdata);
OnReceive?.Invoke(sk, CmdID, resultdata);
2021-12-10 23:38:40 +08:00
}
catch (Exception ex)
{
2023-07-06 14:47:20 +08:00
OutNetLog("数据解析错误");
2021-12-10 23:38:40 +08:00
}
}
}
2023-07-06 14:47:20 +08:00
private void OutNetLog(string msg)
{
OnNetLog?.Invoke(msg);
}
#endregion
#region
/// <summary>
/// 发送心跳包
/// </summary>
/// <param name="sk"></param>
///
2024-01-08 16:19:09 +08:00
private void SendHeartbeatWithIndex(AsyncUserToken token)
2023-07-06 14:47:20 +08:00
{
if (token == null || token.Socket == null || !token.Socket.Connected)
return;
try
{
//OutNetLog(DateTime.Now.ToString() + "发送心跳包");
token.SendIndex = MaxSendIndexNum;
2024-01-08 16:19:09 +08:00
SendHeartbeatMessage(token);
2023-07-06 14:47:20 +08:00
}
catch (Exception e)
{
2024-01-15 11:28:29 +08:00
CloseReady(token);
2023-07-06 14:47:20 +08:00
}
}
2021-12-10 23:38:40 +08:00
/// <summary>
/// 心跳包时钟事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void CheckUpdatetimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
for (int i = 0; i < m_clients.Count(); i++)
{
//接收服务器数据计数
m_clients[i].RevIndex--;
if (m_clients[i].RevIndex <= 0)
{
//判定掉线
2024-01-15 11:28:29 +08:00
CloseReady(m_clients[i]);
2021-12-10 23:38:40 +08:00
return;
}
//发送计数
m_clients[i].SendIndex--;
if (m_clients[i].SendIndex <= 0)//需要发送心跳包了
{
//重置倒计时计数
m_clients[i].SendIndex = MaxSendIndexNum;
2024-01-08 16:19:09 +08:00
SendHeartbeatWithIndex(m_clients[i]);
2021-12-10 23:38:40 +08:00
}
}
}
#endregion
}
}