From 6607b3161dc7a1977c05a8de8830fe065220b66a Mon Sep 17 00:00:00 2001 From: sin365 <353374337@qq.com> Date: Thu, 25 Jan 2024 15:41:00 +0800 Subject: [PATCH] =?UTF-8?q?Json=E9=85=8D=E7=BD=AE=EF=BC=8C=E8=BF=9E?= =?UTF-8?q?=E6=8E=A5=E7=AE=A1=E7=90=86=E5=AE=8C=E5=96=84=EF=BC=8C=E9=80=9F?= =?UTF-8?q?=E5=BA=A6=E8=AE=A1=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- NoSugarNet.ClientCore/AppNoSugarNet.cs | 19 +++ .../Manager/AppLocalClient.cs | 59 ++++++- .../Manager/LocalClient/LocalListener.cs | 6 +- .../Network/NetworkHelper.cs | 2 +- NoSugarNet.ServerCore/Common/Config.cs | 4 +- .../Manager/ClientManager.cs | 9 +- .../Manager/LocalClientManager.cs | 152 ++++++++++++++---- .../ServerLocalClient/ServerLocalClient.cs | 4 + .../Manager/ServerManager.cs | 41 ++++- NoSugarNet.ServerCore/NetStatus.cs | 12 ++ NoSugarNet.ServerCore/NetWork/IOCPNetWork.cs | 2 +- Sample/NoSugarNet.ClientCli/Program.cs | 8 + Sample/NoSugarNet.ServerCli/Config.cs | 63 +++++--- Sample/NoSugarNet.ServerCli/Program.cs | 33 +++- .../PublishProfiles/FolderProfile.pubxml.user | 2 +- 15 files changed, 348 insertions(+), 68 deletions(-) create mode 100644 NoSugarNet.ServerCore/NetStatus.cs diff --git a/NoSugarNet.ClientCore/AppNoSugarNet.cs b/NoSugarNet.ClientCore/AppNoSugarNet.cs index 6ecc256..fe86ca2 100644 --- a/NoSugarNet.ClientCore/AppNoSugarNet.cs +++ b/NoSugarNet.ClientCore/AppNoSugarNet.cs @@ -16,6 +16,13 @@ namespace NoSugarNet.ClientCore public static AppChat chat; public static AppLocalClient local; public static UserDataManager user; + public static System.Timers.Timer _SpeedCheckTimeTimer;//速度检测计时器 + public static int TimerInterval = 1000;//计时器间隔 + + #region 委托和事件 + public delegate void OnUpdateStatusHandler(long resultReciveAllLenght, long resultSendAllLenght); + public static event OnUpdateStatusHandler OnUpdateStatus; + #endregion public static void Init(string IP, int port) { @@ -26,6 +33,18 @@ namespace NoSugarNet.ClientCore local = new AppLocalClient(); user = new UserDataManager(); networkHelper.Init(IP, port); + + _SpeedCheckTimeTimer = new System.Timers.Timer(); + _SpeedCheckTimeTimer.Interval = TimerInterval; + _SpeedCheckTimeTimer.Elapsed += Checktimer_Elapsed; + _SpeedCheckTimeTimer.AutoReset = true; + _SpeedCheckTimeTimer.Enabled = true; + } + + static void Checktimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) + { + local.GetCurrLenght(out long resultReciveAllLenght, out long resultSendAllLenght); + OnUpdateStatus?.Invoke(resultReciveAllLenght, resultSendAllLenght); } } } \ No newline at end of file diff --git a/NoSugarNet.ClientCore/Manager/AppLocalClient.cs b/NoSugarNet.ClientCore/Manager/AppLocalClient.cs index 3679e72..0a346bc 100644 --- a/NoSugarNet.ClientCore/Manager/AppLocalClient.cs +++ b/NoSugarNet.ClientCore/Manager/AppLocalClient.cs @@ -4,7 +4,9 @@ using HaoYueNet.ServerNetwork; using NoSugarNet.ClientCore; using NoSugarNet.ClientCore.Common; using NoSugarNet.ClientCore.Network; +using System.Data; using System.Net; +using static System.Runtime.InteropServices.JavaScript.JSType; namespace ServerCore.Manager { @@ -26,6 +28,18 @@ namespace ServerCore.Manager NetMsg.Instance.RegNetMsgEvent((int)CommandID.CmdTunnelS2CData, Recive_TunnelS2CData); } + public void GetCurrLenght(out long resultReciveAllLenght, out long resultSendAllLenght) + { + resultReciveAllLenght = 0; + resultSendAllLenght = 0; + byte[] Keys = mDictTunnelID2Listeners.Keys.ToArray(); + for (int i = 0; i < Keys.Length; i++) + { + resultReciveAllLenght += mDictTunnelID2Listeners[Keys[i]].mReciveAllLenght; + resultSendAllLenght += mDictTunnelID2Listeners[Keys[i]].mSendAllLenght; + } + } + /// /// 初始化连接,先获取到配置 /// @@ -33,12 +47,13 @@ namespace ServerCore.Manager { foreach (var cfg in mDictTunnelID2Cfg) { - LocalListener listener = new LocalListener(1024, 1024, cfg.Key); + LocalListener listener = new LocalListener(256, 1024, cfg.Key); AppNoSugarNet.log.Debug($"开始监听配置 Tunnel:{cfg.Key},Port:{cfg.Value.Port}"); listener.Init(); listener.Start(new IPEndPoint(IPAddress.Any.Address, (int)cfg.Value.Port)); AddLocalListener(listener); } + } #region 连接字典管理 @@ -124,7 +139,7 @@ namespace ServerCore.Manager } public void Recive_TunnelS2CData(byte[] reqData) { - AppNoSugarNet.log.Debug("Recive_TunnelS2CData"); + //AppNoSugarNet.log.Debug("Recive_TunnelS2CData"); Protobuf_S2C_DATA msg = ProtoBufHelper.DeSerizlize(reqData); OnServerLocalDataCallBack((byte)msg.TunnelID,(byte)msg.Idx, msg.HunterNetCoreData.ToArray()); } @@ -172,6 +187,7 @@ namespace ServerCore.Manager //告知给服务端,来自客户端本地的连接断开 AppNoSugarNet.networkHelper.SendToServer((int)CommandID.CmdTunnelC2SDisconnect, respData); } + /// /// 当服务端本地端口连接 /// @@ -205,7 +221,6 @@ namespace ServerCore.Manager AppNoSugarNet.log.Debug($"OnServerLocalDisconnect {tunnelId},{Idx}"); if (!GetLocalListener(tunnelId, out LocalListener _listener)) return; - _listener.SetRemoteConnectd(Idx,false); _listener.CloseConnectByIdx(Idx); } @@ -220,7 +235,7 @@ namespace ServerCore.Manager /// public void OnServerLocalDataCallBack(byte tunnelId,byte Idx, byte[] data) { - AppNoSugarNet.log.Debug($"OnServerLocalDataCallBack {tunnelId},{Idx},Data长度:{data.Length}"); + //AppNoSugarNet.log.Debug($"OnServerLocalDataCallBack {tunnelId},{Idx},Data长度:{data.Length}"); if (!GetLocalListener(tunnelId, out LocalListener _listener)) return; //解压 @@ -235,9 +250,41 @@ namespace ServerCore.Manager /// public void OnClientTunnelDataCallBack(byte tunnelId,byte Idx, byte[] data) { - AppNoSugarNet.log.Debug($"OnClientTunnelDataCallBack {tunnelId},{Idx}"); + //AppNoSugarNet.log.Debug($"OnClientTunnelDataCallBack {tunnelId},{Idx}"); + + int SlienLenght = 1000; + //判断数据量大时分包 + if (data.Length > SlienLenght) + { + Span tempSpan = data; + Span tempSpanSlien = null; + int PageCount = (int)(data.Length / SlienLenght); + if (data.Length % SlienLenght > 0) + { + PageCount++; + } + + for (int i = 0; i < PageCount; i++) + { + int StartIdx = i * SlienLenght; + if (i != PageCount - 1)//不是最后一个包 + tempSpanSlien = tempSpan.Slice(StartIdx, SlienLenght); + else//最后一个 + tempSpanSlien = tempSpan.Slice(StartIdx); + + SendDataToRemote(tunnelId, Idx, tempSpanSlien.ToArray()); + } + return; + } + SendDataToRemote(tunnelId, Idx, data); + } + + + void SendDataToRemote(byte tunnelId, byte Idx, byte[] data) + { //压缩 data = mCompressAdapter.Compress(data); + byte[] respData = ProtoBufHelper.Serizlize(new Protobuf_C2S_DATA() { TunnelID = tunnelId, @@ -254,10 +301,10 @@ namespace ServerCore.Manager _listener.EnqueueIdxWithMsg(Idx, respData); return; } - //投递给服务端,来自客户端本地的连接数据 AppNoSugarNet.networkHelper.SendToServer((int)CommandID.CmdTunnelC2SData, respData); } #endregion + } } \ No newline at end of file diff --git a/NoSugarNet.ClientCore/Manager/LocalClient/LocalListener.cs b/NoSugarNet.ClientCore/Manager/LocalClient/LocalListener.cs index f8f84c2..58fe869 100644 --- a/NoSugarNet.ClientCore/Manager/LocalClient/LocalListener.cs +++ b/NoSugarNet.ClientCore/Manager/LocalClient/LocalListener.cs @@ -6,6 +6,8 @@ namespace NoSugarNet.ClientCore public class LocalListener : TcpSaeaServer_SourceMode { public byte mTunnelID; + public long mReciveAllLenght; + public long mSendAllLenght; public LocalListener(int numConnections, int receiveBufferSize, byte TunnelID) : base(numConnections, receiveBufferSize) { @@ -40,6 +42,7 @@ namespace NoSugarNet.ClientCore { if (GetSocketByIdx(Idx, out LocalClientInfo _localClientInfo)) { + mSendAllLenght += data.Length; SendToSocket(_localClientInfo._socket, data); } //TODO连接前缓存数据 @@ -59,7 +62,8 @@ namespace NoSugarNet.ClientCore public void DataCallBack(Socket sk, byte[] data) { //AppNoSugarNet.log.Debug("收到消息 数据长度=>" + data.Length); - + //记录接受长度 + mReciveAllLenght += data.Length; if (!GetSocketIdxBySocket(sk, out int Idx)) return; try diff --git a/NoSugarNet.ClientCore/Network/NetworkHelper.cs b/NoSugarNet.ClientCore/Network/NetworkHelper.cs index 977da01..0814d43 100644 --- a/NoSugarNet.ClientCore/Network/NetworkHelper.cs +++ b/NoSugarNet.ClientCore/Network/NetworkHelper.cs @@ -71,7 +71,7 @@ namespace NoSugarNet.ClientCore.Network /// 业务数据 public void GetDataCallBack(int CMDID, int ERRCODE, byte[] data) { - NetworkDeBugLog("收到消息 CMDID =>" + CMDID + " ERRCODE =>" + ERRCODE + " 数据长度=>" + data.Length); + //NetworkDeBugLog("收到消息 CMDID =>" + CMDID + " ERRCODE =>" + ERRCODE + " 数据长度=>" + data.Length); try { //抛出网络数据 diff --git a/NoSugarNet.ServerCore/Common/Config.cs b/NoSugarNet.ServerCore/Common/Config.cs index cb75673..6623b55 100644 --- a/NoSugarNet.ServerCore/Common/Config.cs +++ b/NoSugarNet.ServerCore/Common/Config.cs @@ -5,8 +5,8 @@ namespace NoSugarNet.ServerCore.Common public struct TunnelClientData { public byte TunnelId; - public string ServerLocalIP; - public ushort ServerLocalPort; + public string ServerLocalTargetIP; + public ushort ServerLocalTargetPort; public ushort ClientLocalPort; } diff --git a/NoSugarNet.ServerCore/Manager/ClientManager.cs b/NoSugarNet.ServerCore/Manager/ClientManager.cs index 542aadf..7ffbd32 100644 --- a/NoSugarNet.ServerCore/Manager/ClientManager.cs +++ b/NoSugarNet.ServerCore/Manager/ClientManager.cs @@ -169,9 +169,12 @@ namespace ServerCore.Manager if (!_DictSocketClient.ContainsKey(sk)) return; - Console.WriteLine("标记玩家UID" + _DictSocketClient[sk].UID + "为离线"); - _DictSocketClient[sk].IsOffline = true; - _DictSocketClient[sk].LogOutDT = DateTime.Now; + ClientInfo cinfo = _DictSocketClient[sk]; + Console.WriteLine("标记玩家UID" + cinfo.UID + "为离线"); + cinfo.IsOffline = true; + cinfo.LogOutDT = DateTime.Now; + //断开所有连接 + ServerManager.g_Local.StopAll(cinfo.UID); } public void RemoveClientForSocket(Socket sk) diff --git a/NoSugarNet.ServerCore/Manager/LocalClientManager.cs b/NoSugarNet.ServerCore/Manager/LocalClientManager.cs index 6821f7c..05a7018 100644 --- a/NoSugarNet.ServerCore/Manager/LocalClientManager.cs +++ b/NoSugarNet.ServerCore/Manager/LocalClientManager.cs @@ -5,6 +5,7 @@ using NoSugarNet.ServerCore.Common; using ServerCore.Common; using ServerCore.NetWork; using System.Net.Sockets; +using System.Collections.Generic; namespace ServerCore.Manager { @@ -18,6 +19,11 @@ namespace ServerCore.Manager return (Uid * 10000000) + (Tunnel * 10000) + Idx; } + static long GetUidForCommKey(long CommKey) + { + return CommKey / 10000000; + } + public LocalClientManager() { //初始化压缩适配器,暂时使用0,代表压缩类型 @@ -28,6 +34,18 @@ namespace ServerCore.Manager NetMsg.Instance.RegNetMsgEvent((int)CommandID.CmdTunnelC2SData, Recive_TunnelC2SData); } + public void GetCurrLenght(out long resultReciveAllLenght,out long resultSendAllLenght) + { + resultReciveAllLenght = 0; + resultSendAllLenght = 0; + long[] Keys = mDictCommKey2ServerLocalClients.Keys.ToArray(); + for(int i =0; i < Keys.Length; i++) + { + resultReciveAllLenght += mDictCommKey2ServerLocalClients[Keys[i]].mReciveAllLenght; + resultSendAllLenght += mDictCommKey2ServerLocalClients[Keys[i]].mSendAllLenght; + } + } + #region 连接字典管理 /// /// 追加连接 @@ -43,7 +61,6 @@ namespace ServerCore.Manager mDictCommKey2ServerLocalClients[CommKey] = serverClient; } } - /// /// 删除连接 /// @@ -73,6 +90,54 @@ namespace ServerCore.Manager serverLocalClient = mDictCommKey2ServerLocalClients[CommKey]; return true; } + + void CloseServerLocalClient(long uid, byte tunnelId, byte Idx) + { + //隧道ID定位投递服务端本地连接 + if (!GetServerLocalClient(uid, tunnelId, Idx, out ServerLocalClient _serverLocalClient)) + return; + _serverLocalClient.CloseConntect(); + RemoveServerLocalClient(uid, tunnelId, Idx); + } + + public void GetClientCount(out int ClientUserCount,out int TunnelCount) + { + TunnelCount = mDictCommKey2ServerLocalClients.Count; + long[] CommIDKeys = mDictCommKey2ServerLocalClients.Keys.ToArray(); + List TempHadLocalConnetList = new List(); + for (int i = 0; i < CommIDKeys.Length; i++) + { + long uid = GetUidForCommKey(CommIDKeys[i]); + if(!TempHadLocalConnetList.Contains(uid)) + TempHadLocalConnetList.Add(uid); + } + ClientUserCount = TempHadLocalConnetList.Count; + } + + public void StopAll(long Uid) + { + List TempRemoveCommIDList = new List(); + lock (mDictCommKey2ServerLocalClients) + { + long[] CommIDKeys = mDictCommKey2ServerLocalClients.Keys.ToArray(); + for (int i = 0; i < CommIDKeys.Length; i++) + { + long CommID = CommIDKeys[i]; + long tempUid = GetUidForCommKey(CommID); + if (tempUid == Uid) + TempRemoveCommIDList.Add(CommID); + } + } + + for (int i = 0; i < TempRemoveCommIDList.Count; i++) + { + long CommID = TempRemoveCommIDList[i]; + if (!mDictCommKey2ServerLocalClients.ContainsKey(CommID)) + continue; + ServerLocalClient _serverLoackClient = mDictCommKey2ServerLocalClients[CommID]; + _serverLoackClient.CloseConntect(); + } + } #endregion #region 解析客户端上行数据 @@ -83,7 +148,6 @@ namespace ServerCore.Manager Protobuf_C2S_Connect msg = ProtoBufHelper.DeSerizlize(reqData); OnClientLocalConnect(_c.UID, (byte)msg.TunnelID, (byte)msg.Idx); } - public void Recive_TunnelC2SDisconnect(Socket sk, byte[] reqData) { ClientInfo _c = ServerManager.g_ClientMgr.GetClientForSocket(sk); @@ -94,7 +158,7 @@ namespace ServerCore.Manager public void Recive_TunnelC2SData(Socket sk, byte[] reqData) { ClientInfo _c = ServerManager.g_ClientMgr.GetClientForSocket(sk); - ServerManager.g_Log.Debug("OnTunnelC2SData"); + //ServerManager.g_Log.Debug("OnTunnelC2SData"); Protobuf_C2S_DATA msg = ProtoBufHelper.DeSerizlize(reqData); OnClientTunnelDataCallBack(_c.UID, (byte)msg.TunnelID, (byte)msg.Idx, msg.HunterNetCoreData.ToArray()); } @@ -122,7 +186,7 @@ namespace ServerCore.Manager TunnelClientData tunnelDataCfg = Config.Cfgs[tunnelId]; ServerLocalClient serverLocalClient = new ServerLocalClient(uid, tunnelId, (byte)Idx); //连接成功 - if (!serverLocalClient.Init(tunnelDataCfg.ServerLocalIP, tunnelDataCfg.ServerLocalPort)) + if (!serverLocalClient.Init(tunnelDataCfg.ServerLocalTargetIP, tunnelDataCfg.ServerLocalTargetPort)) { //TODO告知客户端连接失败 @@ -153,10 +217,8 @@ namespace ServerCore.Manager if (!GetServerLocalClient(uid, tunnelId, Idx, out ServerLocalClient serverLocalClient)) return; - //清除服务器数据 - RemoveServerLocalClient(uid, tunnelId, Idx); //断开服务端本地客户端连接 - serverLocalClient.CloseConntect(); + CloseServerLocalClient(uid, tunnelId, Idx); } /// /// 当服务端本地端口连接 @@ -191,7 +253,7 @@ namespace ServerCore.Manager ServerManager.g_Log.Debug($"OnServerLocalDisconnect {uid},{tunnelId},{Idx}"); if (!ServerManager.g_ClientMgr.GetClientByUID(uid, out ClientInfo client)) return; - //添加到服务端本地连接列表 + //移除到服务端本地连接列表 RemoveServerLocalClient(uid, tunnelId, Idx); byte[] respData = ProtoBufHelper.Serizlize(new Protobuf_S2C_Disconnect() @@ -206,6 +268,26 @@ namespace ServerCore.Manager #region 数据投递 /// + /// 来自客户端本地连接投递的Tunnel数据 + /// + /// + /// + /// + public void OnClientTunnelDataCallBack(long uid, byte tunnelId, byte Idx, byte[] data) + { + //ServerManager.g_Log.Debug($"OnClientTunnelDataCallBack {uid},{tunnelId},{Idx}"); + //隧道ID定位投递服务端本地连接 + if (!GetServerLocalClient(uid, tunnelId, Idx, out ServerLocalClient serverLocalClient)) + return; + + //解压 + data = mCompressAdapter.Decompress(data); + //记录数据长度 + serverLocalClient.mSendAllLenght += data.LongLength; + //发送给对应服务端本地连接数据 + serverLocalClient.SendToServer(data); + } + /// /// 来自服务端本地连接投递的Tunnel数据 /// /// @@ -213,13 +295,45 @@ namespace ServerCore.Manager /// public void OnServerLocalDataCallBack(long uid, byte tunnelId,byte Idx, byte[] data) { - ServerManager.g_Log.Debug($"OnServerLocalDataCallBack {uid},{tunnelId},{Idx}"); + //ServerManager.g_Log.Debug($"OnServerLocalDataCallBack {uid},{tunnelId},{Idx}"); + if (!ServerManager.g_ClientMgr.GetClientByUID(uid, out ClientInfo client)) + return; + + int SlienLenght = 1000; + //判断数据量大时分包 + if (data.Length > SlienLenght) + { + Span tempSpan = data; + Span tempSpanSlien = null; + int PageCount = (int)(data.Length / SlienLenght); + if (data.Length % SlienLenght > 0) + { + PageCount++; + } + + for (int i = 0; i < PageCount; i++) + { + int StartIdx = i * SlienLenght; + if (i != PageCount - 1)//不是最后一个包 + tempSpanSlien = tempSpan.Slice(StartIdx, SlienLenght); + else//最后一个 + tempSpanSlien = tempSpan.Slice(StartIdx); + + SendDataToRemote(uid, tunnelId, Idx, tempSpanSlien.ToArray()); + } + return; + } + SendDataToRemote(uid, tunnelId, Idx, data); + } + + void SendDataToRemote(long uid, byte tunnelId, byte Idx, byte[] data) + { if (!ServerManager.g_ClientMgr.GetClientByUID(uid, out ClientInfo client)) return; //压缩 data = mCompressAdapter.Compress(data); - byte[] respData = ProtoBufHelper.Serizlize(new Protobuf_C2S_DATA() + byte[] respData = ProtoBufHelper.Serizlize(new Protobuf_S2C_DATA() { TunnelID = tunnelId, Idx = Idx, @@ -229,24 +343,6 @@ namespace ServerCore.Manager //发送给客户端,指定客户端本地隧道ID ServerManager.g_ClientMgr.ClientSend(client, (int)CommandID.CmdTunnelS2CData, (int)ErrorCode.ErrorOk, respData); } - /// - /// 来自客户端本地连接投递的Tunnel数据 - /// - /// - /// - /// - public void OnClientTunnelDataCallBack(long uid, byte tunnelId, byte Idx, byte[] data) - { - ServerManager.g_Log.Debug($"OnClientTunnelDataCallBack {uid},{tunnelId},{Idx}"); - //隧道ID定位投递服务端本地连接 - if (!GetServerLocalClient(uid, tunnelId, Idx, out ServerLocalClient serverLocalClient)) - return; - - //解压 - data = mCompressAdapter.Decompress(data); - //发送给对应服务端本地连接数据 - serverLocalClient.SendToServer(mCompressAdapter.Decompress(data)); - } #endregion } } \ No newline at end of file diff --git a/NoSugarNet.ServerCore/Manager/ServerLocalClient/ServerLocalClient.cs b/NoSugarNet.ServerCore/Manager/ServerLocalClient/ServerLocalClient.cs index 215ae65..999439a 100644 --- a/NoSugarNet.ServerCore/Manager/ServerLocalClient/ServerLocalClient.cs +++ b/NoSugarNet.ServerCore/Manager/ServerLocalClient/ServerLocalClient.cs @@ -12,6 +12,8 @@ namespace NoSugarNet.ClientCore.Network public long mUID; public byte mTunnelID; public byte mIdx; + public long mReciveAllLenght; + public long mSendAllLenght; public ServerLocalClient(long UID,byte TunnelID, byte Idx) { mUID = UID; @@ -58,6 +60,8 @@ namespace NoSugarNet.ClientCore.Network //NetworkDeBugLog("收到消息 数据长度=>" + data.Length); try { + //记录接收数据长度 + mReciveAllLenght += data.Length; //抛出网络数据 ServerManager.g_Local.OnServerLocalDataCallBack(mUID, mTunnelID, mIdx, data); } diff --git a/NoSugarNet.ServerCore/Manager/ServerManager.cs b/NoSugarNet.ServerCore/Manager/ServerManager.cs index 86d9e5d..0274b9e 100644 --- a/NoSugarNet.ServerCore/Manager/ServerManager.cs +++ b/NoSugarNet.ServerCore/Manager/ServerManager.cs @@ -1,10 +1,11 @@ -using NoSugarNet.ServerCore.Common; +using NoSugarNet.ServerCore; +using NoSugarNet.ServerCore.Common; using ServerCore.NetWork; -using ServerCore.Common; using System.Net; namespace ServerCore.Manager { + public static class ServerManager { public static ClientManager g_ClientMgr; @@ -13,6 +14,15 @@ namespace ServerCore.Manager public static ChatManager g_Chat; public static LocalClientManager g_Local; public static IOCPNetWork g_SocketMgr; + public static System.Timers.Timer _SpeedCheckTimeTimer;//速度检测计时器 + public static int TimerInterval = 1000;//计时器间隔 + static long mLastReciveAllLenght = 0; + static long mSendAllLenght = 0; + static NetStatus netStatus; + #region 委托和事件 + public delegate void OnUpdateStatusHandler(NetStatus Status); + public static event OnUpdateStatusHandler OnUpdateStatus; + #endregion public static void InitServer(int port, Dictionary cfgs) { @@ -25,9 +35,36 @@ namespace ServerCore.Manager g_Local = new LocalClientManager(); //g_SocketMgr = new IOCPNetWork(1024, 1024); g_SocketMgr = new IOCPNetWork(1024, 4096); + + netStatus = new NetStatus(); + g_SocketMgr.Init(); g_SocketMgr.Start(new IPEndPoint(IPAddress.Any.Address, port)); Console.WriteLine("Succeed!"); + + _SpeedCheckTimeTimer = new System.Timers.Timer(); + _SpeedCheckTimeTimer.Interval = TimerInterval; + _SpeedCheckTimeTimer.Elapsed += Checktimer_Elapsed; + _SpeedCheckTimeTimer.AutoReset = true; + _SpeedCheckTimeTimer.Enabled = true; } + + static void Checktimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) + { + g_Local.GetCurrLenght(out long resultReciveAllLenght, out long resultSendAllLenght); + g_Local.GetClientCount(out int ClientUserCount, out int TunnelCount); + NetStatus resutnetStatus = new NetStatus() + { + TunnelCount = TunnelCount, + ClientUserCount = ClientUserCount, + SendAllLenght = resultSendAllLenght, + ReciveAllLenght = resultReciveAllLenght, + ReciveSecSpeed = (resultReciveAllLenght - netStatus.ReciveAllLenght) / (TimerInterval / 1000), + SendSecSpeed = (resultSendAllLenght - netStatus.SendAllLenght) / (TimerInterval / 1000), + }; + netStatus = resutnetStatus; + OnUpdateStatus?.Invoke(resutnetStatus); + } + } } \ No newline at end of file diff --git a/NoSugarNet.ServerCore/NetStatus.cs b/NoSugarNet.ServerCore/NetStatus.cs new file mode 100644 index 0000000..db3d95f --- /dev/null +++ b/NoSugarNet.ServerCore/NetStatus.cs @@ -0,0 +1,12 @@ +namespace NoSugarNet.ServerCore +{ + public struct NetStatus + { + public int ClientUserCount; + public int TunnelCount; + public long ReciveAllLenght; + public long SendAllLenght; + public long ReciveSecSpeed; + public long SendSecSpeed; + } +} diff --git a/NoSugarNet.ServerCore/NetWork/IOCPNetWork.cs b/NoSugarNet.ServerCore/NetWork/IOCPNetWork.cs index f33b821..3706883 100644 --- a/NoSugarNet.ServerCore/NetWork/IOCPNetWork.cs +++ b/NoSugarNet.ServerCore/NetWork/IOCPNetWork.cs @@ -33,7 +33,7 @@ namespace ServerCore.NetWork public void DataCallBack(Socket sk, int CMDID, byte[] data) { - ServerManager.g_Log.Debug("收到消息 CMDID =>" + CMDID + " 数据长度=>" + data.Length); + //ServerManager.g_Log.Debug("收到消息 CMDID =>" + CMDID + " 数据长度=>" + data.Length); try { //抛出网络数据 diff --git a/Sample/NoSugarNet.ClientCli/Program.cs b/Sample/NoSugarNet.ClientCli/Program.cs index 49c7c29..79c3bd9 100644 --- a/Sample/NoSugarNet.ClientCli/Program.cs +++ b/Sample/NoSugarNet.ClientCli/Program.cs @@ -4,6 +4,7 @@ namespace NoSugarNet.ClientCli { internal class Program { + static string Title = "NoSugarNetClient"; static void Main(string[] args) { if (!Config.LoadConfig()) @@ -12,11 +13,18 @@ namespace NoSugarNet.ClientCli Console.ReadLine(); return; } + AppNoSugarNet.OnUpdateStatus += OnUpdateStatus; AppNoSugarNet.Init(Config.ServerIP, Config.ServerPort); while (true) { Console.ReadLine(); } } + static void OnUpdateStatus(long resultReciveAllLenght, long resultSendAllLenght) + { + Console.Title = $"{Title} Recive:{resultReciveAllLenght} Send:{resultSendAllLenght}"; + Console.WriteLine($"{Title} Recive:{resultReciveAllLenght} Send:{resultSendAllLenght}"); + } } + } \ No newline at end of file diff --git a/Sample/NoSugarNet.ServerCli/Config.cs b/Sample/NoSugarNet.ServerCli/Config.cs index eb8c776..75251dd 100644 --- a/Sample/NoSugarNet.ServerCli/Config.cs +++ b/Sample/NoSugarNet.ServerCli/Config.cs @@ -1,39 +1,60 @@ -using NoSugarNet.ServerCore.Common; -using System.Text; +using System.Text; +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Unicode; namespace NoSugarNet.ServerCli { + public class ConfigDataModel + { + public int ServerPort { get; set; } + public List TunnelList { get; set; } + } + + public class ConfigDataModel_Single + { + public string ServerLocalTargetIP { get; set; } + public int ServerLocalTargetPort { get; set; } + public int ClientLocalPort { get; set; } + } + public static class Config { - public static Dictionary Cfgs = new Dictionary(); + public static ConfigDataModel cfg; public static bool LoadConfig() { try { - StreamReader sr = new StreamReader(System.Environment.CurrentDirectory + "//config.cfg", Encoding.Default); - String line; - while (!string.IsNullOrEmpty((line = sr.ReadLine()))) + string path = System.Environment.CurrentDirectory + "//config.cfg"; + if (!File.Exists(path)) { - if (!line.Contains(":")) - continue; - try + ConfigDataModel sampleCfg = new ConfigDataModel { - TunnelClientData cfg = new TunnelClientData() + ServerPort = 1000, + TunnelList = new List() { - TunnelId = Convert.ToByte(line.Split(':')[0].Trim()), - ServerLocalIP = line.Split(':')[1].Trim(), - ServerLocalPort = Convert.ToUInt16(line.Split(':')[2].Trim()), - ClientLocalPort = Convert.ToUInt16(line.Split(':')[3].Trim()) - }; - Cfgs[cfg.TunnelId] = cfg; - } - catch + new ConfigDataModel_Single(){ ServerLocalTargetIP = "127.0.0.1",ServerLocalTargetPort=3389,ClientLocalPort = 10001}, + new ConfigDataModel_Single(){ ServerLocalTargetIP = "127.0.0.1",ServerLocalTargetPort=3389,ClientLocalPort = 10002} + } + }; + + string jsonString = JsonSerializer.Serialize(sampleCfg, new JsonSerializerOptions() { - continue; - } + // 整齐打印 + WriteIndented = true, + //重新编码,解决中文乱码问题 + Encoder = JavaScriptEncoder.Create(UnicodeRanges.All) + }); + System.IO.File.WriteAllText(path, jsonString, Encoding.UTF8); + + Console.WriteLine("未找到配置,已生成模板,请浏览" + path); + return false; } + StreamReader sr = new StreamReader(path, Encoding.Default); + String jsonstr = sr.ReadToEnd(); + cfg = JsonSerializer.Deserialize(jsonstr); sr.Close(); - if (Cfgs.Count > 0) + if (cfg?.TunnelList.Count > 0) return true; else return false; diff --git a/Sample/NoSugarNet.ServerCli/Program.cs b/Sample/NoSugarNet.ServerCli/Program.cs index b2e542b..e7a0e8a 100644 --- a/Sample/NoSugarNet.ServerCli/Program.cs +++ b/Sample/NoSugarNet.ServerCli/Program.cs @@ -1,9 +1,12 @@ -using ServerCore.Manager; +using NoSugarNet.ServerCore; +using NoSugarNet.ServerCore.Common; +using ServerCore.Manager; namespace NoSugarNet.ServerCli { internal class Program { + static string Title = "NoSugarNetServer"; static void Main(string[] args) { Console.ForegroundColor = ConsoleColor.Green; @@ -13,12 +16,38 @@ namespace NoSugarNet.ServerCli Console.ReadLine(); return; } + Dictionary dictTunnel = new Dictionary(); + for (int i = 0; i < Config.cfg.TunnelList.Count; i++) + { + ConfigDataModel_Single cfgSingle = Config.cfg.TunnelList[i]; + dictTunnel[(byte)i] = new TunnelClientData() + { + TunnelId = (byte)i, + ServerLocalTargetIP = cfgSingle.ServerLocalTargetIP, + ServerLocalTargetPort = (ushort)cfgSingle.ServerLocalTargetPort, + ClientLocalPort = (ushort)cfgSingle.ClientLocalPort, + }; + } + + ServerManager.OnUpdateStatus += OnUpdateStatus; + ServerManager.InitServer(Config.cfg.ServerPort, dictTunnel); - ServerManager.InitServer(1000,Config.Cfgs); while (true) { Console.ReadLine(); } } + + static void OnUpdateStatus(NetStatus netState) + { + string info = $"{Title} RecLen:{netState.ReciveAllLenght} SendLen:{netState.SendAllLenght} tUserNum:{netState.ClientUserCount} tTunnelNum:{netState.TunnelCount} recSpeed:{ConvertBytesToKilobytes(netState.ReciveSecSpeed)}K/s sendSpeed:{ConvertBytesToKilobytes(netState.SendSecSpeed)}K/s"; + Console.Title = info; + Console.WriteLine(info); + } + + private static double ConvertBytesToKilobytes(long bytes) + { + return Math.Round((double)bytes / 1024, 2); + } } } \ No newline at end of file diff --git a/Sample/NoSugarNet.ServerCli/Properties/PublishProfiles/FolderProfile.pubxml.user b/Sample/NoSugarNet.ServerCli/Properties/PublishProfiles/FolderProfile.pubxml.user index fa68c26..c6eb72d 100644 --- a/Sample/NoSugarNet.ServerCli/Properties/PublishProfiles/FolderProfile.pubxml.user +++ b/Sample/NoSugarNet.ServerCli/Properties/PublishProfiles/FolderProfile.pubxml.user @@ -4,7 +4,7 @@ https://go.microsoft.com/fwlink/?LinkID=208121. --> - True|2024-01-23T08:36:21.1141328Z; + True|2024-01-23T10:28:01.1220581Z;True|2024-01-23T16:36:21.1141328+08:00; \ No newline at end of file