Json配置,连接管理完善,速度计数

This commit is contained in:
sin365 2024-01-25 15:41:00 +08:00
parent d0af35c28a
commit 6607b3161d
15 changed files with 348 additions and 68 deletions

View File

@ -16,6 +16,13 @@ namespace NoSugarNet.ClientCore
public static AppChat chat; public static AppChat chat;
public static AppLocalClient local; public static AppLocalClient local;
public static UserDataManager user; 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) public static void Init(string IP, int port)
{ {
@ -26,6 +33,18 @@ namespace NoSugarNet.ClientCore
local = new AppLocalClient(); local = new AppLocalClient();
user = new UserDataManager(); user = new UserDataManager();
networkHelper.Init(IP, port); 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);
} }
} }
} }

View File

@ -4,7 +4,9 @@ using HaoYueNet.ServerNetwork;
using NoSugarNet.ClientCore; using NoSugarNet.ClientCore;
using NoSugarNet.ClientCore.Common; using NoSugarNet.ClientCore.Common;
using NoSugarNet.ClientCore.Network; using NoSugarNet.ClientCore.Network;
using System.Data;
using System.Net; using System.Net;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace ServerCore.Manager namespace ServerCore.Manager
{ {
@ -26,6 +28,18 @@ namespace ServerCore.Manager
NetMsg.Instance.RegNetMsgEvent((int)CommandID.CmdTunnelS2CData, Recive_TunnelS2CData); 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;
}
}
/// <summary> /// <summary>
/// 初始化连接,先获取到配置 /// 初始化连接,先获取到配置
/// </summary> /// </summary>
@ -33,12 +47,13 @@ namespace ServerCore.Manager
{ {
foreach (var cfg in mDictTunnelID2Cfg) 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}"); AppNoSugarNet.log.Debug($"开始监听配置 Tunnel:{cfg.Key},Port:{cfg.Value.Port}");
listener.Init(); listener.Init();
listener.Start(new IPEndPoint(IPAddress.Any.Address, (int)cfg.Value.Port)); listener.Start(new IPEndPoint(IPAddress.Any.Address, (int)cfg.Value.Port));
AddLocalListener(listener); AddLocalListener(listener);
} }
} }
#region #region
@ -124,7 +139,7 @@ namespace ServerCore.Manager
} }
public void Recive_TunnelS2CData(byte[] reqData) public void Recive_TunnelS2CData(byte[] reqData)
{ {
AppNoSugarNet.log.Debug("Recive_TunnelS2CData"); //AppNoSugarNet.log.Debug("Recive_TunnelS2CData");
Protobuf_S2C_DATA msg = ProtoBufHelper.DeSerizlize<Protobuf_S2C_DATA>(reqData); Protobuf_S2C_DATA msg = ProtoBufHelper.DeSerizlize<Protobuf_S2C_DATA>(reqData);
OnServerLocalDataCallBack((byte)msg.TunnelID,(byte)msg.Idx, msg.HunterNetCoreData.ToArray()); OnServerLocalDataCallBack((byte)msg.TunnelID,(byte)msg.Idx, msg.HunterNetCoreData.ToArray());
} }
@ -172,6 +187,7 @@ namespace ServerCore.Manager
//告知给服务端,来自客户端本地的连接断开 //告知给服务端,来自客户端本地的连接断开
AppNoSugarNet.networkHelper.SendToServer((int)CommandID.CmdTunnelC2SDisconnect, respData); AppNoSugarNet.networkHelper.SendToServer((int)CommandID.CmdTunnelC2SDisconnect, respData);
} }
/// <summary> /// <summary>
/// 当服务端本地端口连接 /// 当服务端本地端口连接
/// </summary> /// </summary>
@ -205,7 +221,6 @@ namespace ServerCore.Manager
AppNoSugarNet.log.Debug($"OnServerLocalDisconnect {tunnelId},{Idx}"); AppNoSugarNet.log.Debug($"OnServerLocalDisconnect {tunnelId},{Idx}");
if (!GetLocalListener(tunnelId, out LocalListener _listener)) if (!GetLocalListener(tunnelId, out LocalListener _listener))
return; return;
_listener.SetRemoteConnectd(Idx,false); _listener.SetRemoteConnectd(Idx,false);
_listener.CloseConnectByIdx(Idx); _listener.CloseConnectByIdx(Idx);
} }
@ -220,7 +235,7 @@ namespace ServerCore.Manager
/// <param name="data"></param> /// <param name="data"></param>
public void OnServerLocalDataCallBack(byte tunnelId,byte Idx, byte[] data) 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)) if (!GetLocalListener(tunnelId, out LocalListener _listener))
return; return;
//解压 //解压
@ -235,9 +250,41 @@ namespace ServerCore.Manager
/// <param name="data"></param> /// <param name="data"></param>
public void OnClientTunnelDataCallBack(byte tunnelId,byte Idx, byte[] data) 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<byte> tempSpan = data;
Span<byte> 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); data = mCompressAdapter.Compress(data);
byte[] respData = ProtoBufHelper.Serizlize(new Protobuf_C2S_DATA() byte[] respData = ProtoBufHelper.Serizlize(new Protobuf_C2S_DATA()
{ {
TunnelID = tunnelId, TunnelID = tunnelId,
@ -254,10 +301,10 @@ namespace ServerCore.Manager
_listener.EnqueueIdxWithMsg(Idx, respData); _listener.EnqueueIdxWithMsg(Idx, respData);
return; return;
} }
//投递给服务端,来自客户端本地的连接数据 //投递给服务端,来自客户端本地的连接数据
AppNoSugarNet.networkHelper.SendToServer((int)CommandID.CmdTunnelC2SData, respData); AppNoSugarNet.networkHelper.SendToServer((int)CommandID.CmdTunnelC2SData, respData);
} }
#endregion #endregion
} }
} }

View File

@ -6,6 +6,8 @@ namespace NoSugarNet.ClientCore
public class LocalListener : TcpSaeaServer_SourceMode public class LocalListener : TcpSaeaServer_SourceMode
{ {
public byte mTunnelID; public byte mTunnelID;
public long mReciveAllLenght;
public long mSendAllLenght;
public LocalListener(int numConnections, int receiveBufferSize, byte TunnelID) public LocalListener(int numConnections, int receiveBufferSize, byte TunnelID)
: base(numConnections, receiveBufferSize) : base(numConnections, receiveBufferSize)
{ {
@ -40,6 +42,7 @@ namespace NoSugarNet.ClientCore
{ {
if (GetSocketByIdx(Idx, out LocalClientInfo _localClientInfo)) if (GetSocketByIdx(Idx, out LocalClientInfo _localClientInfo))
{ {
mSendAllLenght += data.Length;
SendToSocket(_localClientInfo._socket, data); SendToSocket(_localClientInfo._socket, data);
} }
//TODO连接前缓存数据 //TODO连接前缓存数据
@ -59,7 +62,8 @@ namespace NoSugarNet.ClientCore
public void DataCallBack(Socket sk, byte[] data) public void DataCallBack(Socket sk, byte[] data)
{ {
//AppNoSugarNet.log.Debug("收到消息 数据长度=>" + data.Length); //AppNoSugarNet.log.Debug("收到消息 数据长度=>" + data.Length);
//记录接受长度
mReciveAllLenght += data.Length;
if (!GetSocketIdxBySocket(sk, out int Idx)) if (!GetSocketIdxBySocket(sk, out int Idx))
return; return;
try try

View File

@ -71,7 +71,7 @@ namespace NoSugarNet.ClientCore.Network
/// <param name="data">业务数据</param> /// <param name="data">业务数据</param>
public void GetDataCallBack(int CMDID, int ERRCODE, byte[] data) public void GetDataCallBack(int CMDID, int ERRCODE, byte[] data)
{ {
NetworkDeBugLog("收到消息 CMDID =>" + CMDID + " ERRCODE =>" + ERRCODE + " 数据长度=>" + data.Length); //NetworkDeBugLog("收到消息 CMDID =>" + CMDID + " ERRCODE =>" + ERRCODE + " 数据长度=>" + data.Length);
try try
{ {
//抛出网络数据 //抛出网络数据

View File

@ -5,8 +5,8 @@ namespace NoSugarNet.ServerCore.Common
public struct TunnelClientData public struct TunnelClientData
{ {
public byte TunnelId; public byte TunnelId;
public string ServerLocalIP; public string ServerLocalTargetIP;
public ushort ServerLocalPort; public ushort ServerLocalTargetPort;
public ushort ClientLocalPort; public ushort ClientLocalPort;
} }

View File

@ -169,9 +169,12 @@ namespace ServerCore.Manager
if (!_DictSocketClient.ContainsKey(sk)) if (!_DictSocketClient.ContainsKey(sk))
return; return;
Console.WriteLine("标记玩家UID" + _DictSocketClient[sk].UID + "为离线"); ClientInfo cinfo = _DictSocketClient[sk];
_DictSocketClient[sk].IsOffline = true; Console.WriteLine("标记玩家UID" + cinfo.UID + "为离线");
_DictSocketClient[sk].LogOutDT = DateTime.Now; cinfo.IsOffline = true;
cinfo.LogOutDT = DateTime.Now;
//断开所有连接
ServerManager.g_Local.StopAll(cinfo.UID);
} }
public void RemoveClientForSocket(Socket sk) public void RemoveClientForSocket(Socket sk)

View File

@ -5,6 +5,7 @@ using NoSugarNet.ServerCore.Common;
using ServerCore.Common; using ServerCore.Common;
using ServerCore.NetWork; using ServerCore.NetWork;
using System.Net.Sockets; using System.Net.Sockets;
using System.Collections.Generic;
namespace ServerCore.Manager namespace ServerCore.Manager
{ {
@ -18,6 +19,11 @@ namespace ServerCore.Manager
return (Uid * 10000000) + (Tunnel * 10000) + Idx; return (Uid * 10000000) + (Tunnel * 10000) + Idx;
} }
static long GetUidForCommKey(long CommKey)
{
return CommKey / 10000000;
}
public LocalClientManager() public LocalClientManager()
{ {
//初始化压缩适配器暂时使用0代表压缩类型 //初始化压缩适配器暂时使用0代表压缩类型
@ -28,6 +34,18 @@ namespace ServerCore.Manager
NetMsg.Instance.RegNetMsgEvent((int)CommandID.CmdTunnelC2SData, Recive_TunnelC2SData); 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 #region
/// <summary> /// <summary>
/// 追加连接 /// 追加连接
@ -43,7 +61,6 @@ namespace ServerCore.Manager
mDictCommKey2ServerLocalClients[CommKey] = serverClient; mDictCommKey2ServerLocalClients[CommKey] = serverClient;
} }
} }
/// <summary> /// <summary>
/// 删除连接 /// 删除连接
/// </summary> /// </summary>
@ -73,6 +90,54 @@ namespace ServerCore.Manager
serverLocalClient = mDictCommKey2ServerLocalClients[CommKey]; serverLocalClient = mDictCommKey2ServerLocalClients[CommKey];
return true; 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<long> TempHadLocalConnetList = new List<long>();
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<long> TempRemoveCommIDList = new List<long>();
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 #endregion
#region #region
@ -83,7 +148,6 @@ namespace ServerCore.Manager
Protobuf_C2S_Connect msg = ProtoBufHelper.DeSerizlize<Protobuf_C2S_Connect>(reqData); Protobuf_C2S_Connect msg = ProtoBufHelper.DeSerizlize<Protobuf_C2S_Connect>(reqData);
OnClientLocalConnect(_c.UID, (byte)msg.TunnelID, (byte)msg.Idx); OnClientLocalConnect(_c.UID, (byte)msg.TunnelID, (byte)msg.Idx);
} }
public void Recive_TunnelC2SDisconnect(Socket sk, byte[] reqData) public void Recive_TunnelC2SDisconnect(Socket sk, byte[] reqData)
{ {
ClientInfo _c = ServerManager.g_ClientMgr.GetClientForSocket(sk); ClientInfo _c = ServerManager.g_ClientMgr.GetClientForSocket(sk);
@ -94,7 +158,7 @@ namespace ServerCore.Manager
public void Recive_TunnelC2SData(Socket sk, byte[] reqData) public void Recive_TunnelC2SData(Socket sk, byte[] reqData)
{ {
ClientInfo _c = ServerManager.g_ClientMgr.GetClientForSocket(sk); ClientInfo _c = ServerManager.g_ClientMgr.GetClientForSocket(sk);
ServerManager.g_Log.Debug("OnTunnelC2SData"); //ServerManager.g_Log.Debug("OnTunnelC2SData");
Protobuf_C2S_DATA msg = ProtoBufHelper.DeSerizlize<Protobuf_C2S_DATA>(reqData); Protobuf_C2S_DATA msg = ProtoBufHelper.DeSerizlize<Protobuf_C2S_DATA>(reqData);
OnClientTunnelDataCallBack(_c.UID, (byte)msg.TunnelID, (byte)msg.Idx, msg.HunterNetCoreData.ToArray()); OnClientTunnelDataCallBack(_c.UID, (byte)msg.TunnelID, (byte)msg.Idx, msg.HunterNetCoreData.ToArray());
} }
@ -122,7 +186,7 @@ namespace ServerCore.Manager
TunnelClientData tunnelDataCfg = Config.Cfgs[tunnelId]; TunnelClientData tunnelDataCfg = Config.Cfgs[tunnelId];
ServerLocalClient serverLocalClient = new ServerLocalClient(uid, tunnelId, (byte)Idx); ServerLocalClient serverLocalClient = new ServerLocalClient(uid, tunnelId, (byte)Idx);
//连接成功 //连接成功
if (!serverLocalClient.Init(tunnelDataCfg.ServerLocalIP, tunnelDataCfg.ServerLocalPort)) if (!serverLocalClient.Init(tunnelDataCfg.ServerLocalTargetIP, tunnelDataCfg.ServerLocalTargetPort))
{ {
//TODO告知客户端连接失败 //TODO告知客户端连接失败
@ -153,10 +217,8 @@ namespace ServerCore.Manager
if (!GetServerLocalClient(uid, tunnelId, Idx, out ServerLocalClient serverLocalClient)) if (!GetServerLocalClient(uid, tunnelId, Idx, out ServerLocalClient serverLocalClient))
return; return;
//清除服务器数据
RemoveServerLocalClient(uid, tunnelId, Idx);
//断开服务端本地客户端连接 //断开服务端本地客户端连接
serverLocalClient.CloseConntect(); CloseServerLocalClient(uid, tunnelId, Idx);
} }
/// <summary> /// <summary>
/// 当服务端本地端口连接 /// 当服务端本地端口连接
@ -191,7 +253,7 @@ namespace ServerCore.Manager
ServerManager.g_Log.Debug($"OnServerLocalDisconnect {uid},{tunnelId},{Idx}"); ServerManager.g_Log.Debug($"OnServerLocalDisconnect {uid},{tunnelId},{Idx}");
if (!ServerManager.g_ClientMgr.GetClientByUID(uid, out ClientInfo client)) if (!ServerManager.g_ClientMgr.GetClientByUID(uid, out ClientInfo client))
return; return;
//添加到服务端本地连接列表 //移除到服务端本地连接列表
RemoveServerLocalClient(uid, tunnelId, Idx); RemoveServerLocalClient(uid, tunnelId, Idx);
byte[] respData = ProtoBufHelper.Serizlize(new Protobuf_S2C_Disconnect() byte[] respData = ProtoBufHelper.Serizlize(new Protobuf_S2C_Disconnect()
@ -206,6 +268,26 @@ namespace ServerCore.Manager
#region #region
/// <summary> /// <summary>
/// 来自客户端本地连接投递的Tunnel数据
/// </summary>
/// <param name="uid"></param>
/// <param name="tunnelId"></param>
/// <param name="data"></param>
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);
}
/// <summary>
/// 来自服务端本地连接投递的Tunnel数据 /// 来自服务端本地连接投递的Tunnel数据
/// </summary> /// </summary>
/// <param name="uid"></param> /// <param name="uid"></param>
@ -213,13 +295,45 @@ namespace ServerCore.Manager
/// <param name="data"></param> /// <param name="data"></param>
public void OnServerLocalDataCallBack(long uid, byte tunnelId,byte Idx, byte[] data) 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<byte> tempSpan = data;
Span<byte> 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)) if (!ServerManager.g_ClientMgr.GetClientByUID(uid, out ClientInfo client))
return; return;
//压缩 //压缩
data = mCompressAdapter.Compress(data); data = mCompressAdapter.Compress(data);
byte[] respData = ProtoBufHelper.Serizlize(new Protobuf_C2S_DATA() byte[] respData = ProtoBufHelper.Serizlize(new Protobuf_S2C_DATA()
{ {
TunnelID = tunnelId, TunnelID = tunnelId,
Idx = Idx, Idx = Idx,
@ -229,24 +343,6 @@ namespace ServerCore.Manager
//发送给客户端指定客户端本地隧道ID //发送给客户端指定客户端本地隧道ID
ServerManager.g_ClientMgr.ClientSend(client, (int)CommandID.CmdTunnelS2CData, (int)ErrorCode.ErrorOk, respData); ServerManager.g_ClientMgr.ClientSend(client, (int)CommandID.CmdTunnelS2CData, (int)ErrorCode.ErrorOk, respData);
} }
/// <summary>
/// 来自客户端本地连接投递的Tunnel数据
/// </summary>
/// <param name="uid"></param>
/// <param name="tunnelId"></param>
/// <param name="data"></param>
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 #endregion
} }
} }

View File

@ -12,6 +12,8 @@ namespace NoSugarNet.ClientCore.Network
public long mUID; public long mUID;
public byte mTunnelID; public byte mTunnelID;
public byte mIdx; public byte mIdx;
public long mReciveAllLenght;
public long mSendAllLenght;
public ServerLocalClient(long UID,byte TunnelID, byte Idx) public ServerLocalClient(long UID,byte TunnelID, byte Idx)
{ {
mUID = UID; mUID = UID;
@ -58,6 +60,8 @@ namespace NoSugarNet.ClientCore.Network
//NetworkDeBugLog("收到消息 数据长度=>" + data.Length); //NetworkDeBugLog("收到消息 数据长度=>" + data.Length);
try try
{ {
//记录接收数据长度
mReciveAllLenght += data.Length;
//抛出网络数据 //抛出网络数据
ServerManager.g_Local.OnServerLocalDataCallBack(mUID, mTunnelID, mIdx, data); ServerManager.g_Local.OnServerLocalDataCallBack(mUID, mTunnelID, mIdx, data);
} }

View File

@ -1,10 +1,11 @@
using NoSugarNet.ServerCore.Common; using NoSugarNet.ServerCore;
using NoSugarNet.ServerCore.Common;
using ServerCore.NetWork; using ServerCore.NetWork;
using ServerCore.Common;
using System.Net; using System.Net;
namespace ServerCore.Manager namespace ServerCore.Manager
{ {
public static class ServerManager public static class ServerManager
{ {
public static ClientManager g_ClientMgr; public static ClientManager g_ClientMgr;
@ -13,6 +14,15 @@ namespace ServerCore.Manager
public static ChatManager g_Chat; public static ChatManager g_Chat;
public static LocalClientManager g_Local; public static LocalClientManager g_Local;
public static IOCPNetWork g_SocketMgr; 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<byte, TunnelClientData> cfgs) public static void InitServer(int port, Dictionary<byte, TunnelClientData> cfgs)
{ {
@ -25,9 +35,36 @@ namespace ServerCore.Manager
g_Local = new LocalClientManager(); g_Local = new LocalClientManager();
//g_SocketMgr = new IOCPNetWork(1024, 1024); //g_SocketMgr = new IOCPNetWork(1024, 1024);
g_SocketMgr = new IOCPNetWork(1024, 4096); g_SocketMgr = new IOCPNetWork(1024, 4096);
netStatus = new NetStatus();
g_SocketMgr.Init(); g_SocketMgr.Init();
g_SocketMgr.Start(new IPEndPoint(IPAddress.Any.Address, port)); g_SocketMgr.Start(new IPEndPoint(IPAddress.Any.Address, port));
Console.WriteLine("Succeed!"); 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);
}
} }
} }

View File

@ -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;
}
}

View File

@ -33,7 +33,7 @@ namespace ServerCore.NetWork
public void DataCallBack(Socket sk, int CMDID, byte[] data) 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 try
{ {
//抛出网络数据 //抛出网络数据

View File

@ -4,6 +4,7 @@ namespace NoSugarNet.ClientCli
{ {
internal class Program internal class Program
{ {
static string Title = "NoSugarNetClient";
static void Main(string[] args) static void Main(string[] args)
{ {
if (!Config.LoadConfig()) if (!Config.LoadConfig())
@ -12,11 +13,18 @@ namespace NoSugarNet.ClientCli
Console.ReadLine(); Console.ReadLine();
return; return;
} }
AppNoSugarNet.OnUpdateStatus += OnUpdateStatus;
AppNoSugarNet.Init(Config.ServerIP, Config.ServerPort); AppNoSugarNet.Init(Config.ServerIP, Config.ServerPort);
while (true) while (true)
{ {
Console.ReadLine(); Console.ReadLine();
} }
} }
static void OnUpdateStatus(long resultReciveAllLenght, long resultSendAllLenght)
{
Console.Title = $"{Title} Recive:{resultReciveAllLenght} Send:{resultSendAllLenght}";
Console.WriteLine($"{Title} Recive:{resultReciveAllLenght} Send:{resultSendAllLenght}");
}
} }
} }

View File

@ -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 namespace NoSugarNet.ServerCli
{ {
public class ConfigDataModel
{
public int ServerPort { get; set; }
public List<ConfigDataModel_Single> 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 class Config
{ {
public static Dictionary<byte, TunnelClientData> Cfgs = new Dictionary<byte, TunnelClientData>(); public static ConfigDataModel cfg;
public static bool LoadConfig() public static bool LoadConfig()
{ {
try try
{ {
StreamReader sr = new StreamReader(System.Environment.CurrentDirectory + "//config.cfg", Encoding.Default); string path = System.Environment.CurrentDirectory + "//config.cfg";
String line; if (!File.Exists(path))
while (!string.IsNullOrEmpty((line = sr.ReadLine())))
{ {
if (!line.Contains(":")) ConfigDataModel sampleCfg = new ConfigDataModel
continue;
try
{ {
TunnelClientData cfg = new TunnelClientData() ServerPort = 1000,
TunnelList = new List<ConfigDataModel_Single>()
{ {
TunnelId = Convert.ToByte(line.Split(':')[0].Trim()), new ConfigDataModel_Single(){ ServerLocalTargetIP = "127.0.0.1",ServerLocalTargetPort=3389,ClientLocalPort = 10001},
ServerLocalIP = line.Split(':')[1].Trim(), new ConfigDataModel_Single(){ ServerLocalTargetIP = "127.0.0.1",ServerLocalTargetPort=3389,ClientLocalPort = 10002}
ServerLocalPort = Convert.ToUInt16(line.Split(':')[2].Trim()), }
ClientLocalPort = Convert.ToUInt16(line.Split(':')[3].Trim()) };
};
Cfgs[cfg.TunnelId] = cfg; string jsonString = JsonSerializer.Serialize(sampleCfg, new JsonSerializerOptions()
}
catch
{ {
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<ConfigDataModel>(jsonstr);
sr.Close(); sr.Close();
if (Cfgs.Count > 0) if (cfg?.TunnelList.Count > 0)
return true; return true;
else else
return false; return false;

View File

@ -1,9 +1,12 @@
using ServerCore.Manager; using NoSugarNet.ServerCore;
using NoSugarNet.ServerCore.Common;
using ServerCore.Manager;
namespace NoSugarNet.ServerCli namespace NoSugarNet.ServerCli
{ {
internal class Program internal class Program
{ {
static string Title = "NoSugarNetServer";
static void Main(string[] args) static void Main(string[] args)
{ {
Console.ForegroundColor = ConsoleColor.Green; Console.ForegroundColor = ConsoleColor.Green;
@ -13,12 +16,38 @@ namespace NoSugarNet.ServerCli
Console.ReadLine(); Console.ReadLine();
return; return;
} }
Dictionary<byte, TunnelClientData> dictTunnel = new Dictionary<byte, TunnelClientData>();
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) while (true)
{ {
Console.ReadLine(); 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);
}
} }
} }

View File

@ -4,7 +4,7 @@ https://go.microsoft.com/fwlink/?LinkID=208121.
--> -->
<Project> <Project>
<PropertyGroup> <PropertyGroup>
<History>True|2024-01-23T08:36:21.1141328Z;</History> <History>True|2024-01-23T10:28:01.1220581Z;True|2024-01-23T16:36:21.1141328+08:00;</History>
<LastFailureDetails /> <LastFailureDetails />
</PropertyGroup> </PropertyGroup>
</Project> </Project>