Compare commits
12 Commits
release_ol
...
master
Author | SHA1 | Date | |
---|---|---|---|
8fd9761eb2 | |||
744c29d60b | |||
3036ef0e05 | |||
c1a3650a95 | |||
665ef09bf7 | |||
ae44b8eba9 | |||
25ad38edc5 | |||
0323b616f4 | |||
7f79e74599 | |||
83a01dae73 | |||
eae301b93d | |||
b58ab0cf2f |
@ -11,8 +11,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HaoYueNet.ServerNetwork", "
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HaoYueNet.ClientNetwork", "NetLib\HaoYueNet.ClientNetwork\HaoYueNet.ClientNetwork.csproj", "{696F6AAE-2D41-48F7-8FCD-E95CFE2A6519}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HaoYueNet.ClientNetworkNet4x", "NetLib\HaoYueNet.ClientNetworkNet4x\HaoYueNet.ClientNetworkNet4x.csproj", "{A741610F-29B9-4F0E-9A3D-0B3E1318F031}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ServerCore", "Simple\ServerCore\ServerCore.csproj", "{3F26CB3D-ECD1-4D50-8AE6-EB6762CBACF6}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Protobuf", "Simple\Protobuf\Protobuf.csproj", "{E5AE46D9-D809-4E87-8ADD-B1BD28ED60E9}"
|
||||
@ -25,11 +23,11 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Client-Cli", "Simple\Client
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NetLib_Standard2", "NetLib_Standard2", "{F4C45C48-8011-4782-B0B3-99164D611A6C}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HaoYueNet.ClientNetworkNet.Standard2", "NetLib_Standard2\HaoYueNet.ClientNetworkNet.Standard2\HaoYueNet.ClientNetworkNet.Standard2.csproj", "{16AF64F5-6BED-4BD5-AD41-39816AD56769}"
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HaoYueNet.ClientNetwork.Standard2", "NetLib_Standard2\HaoYueNet.ClientNetworkNet.Standard2\HaoYueNet.ClientNetwork.Standard2.csproj", "{16AF64F5-6BED-4BD5-AD41-39816AD56769}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HaoYueNet.ServerNetwork.Standard2", "NetLib_Standard2\HaoYueNet.ServerNetwork.Standard2\HaoYueNet.ServerNetwork.Standard2.csproj", "{6BACBAAB-3777-4165-A2F7-7F9B517286B4}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HaoYueNet.ServerNetworkNet4x", "NetLib\HaoYueNet.ServerNetworkNet4x\HaoYueNet.ServerNetworkNet4x.csproj", "{036F9BD9-308C-4194-AB40-C5952EF0E9F5}"
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ClientSaeaTest", "Simple\ClientSaeaTest\ClientSaeaTest.csproj", "{AE22B541-A21E-48F1-9913-C1ACEBF21874}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
@ -45,10 +43,6 @@ Global
|
||||
{696F6AAE-2D41-48F7-8FCD-E95CFE2A6519}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{696F6AAE-2D41-48F7-8FCD-E95CFE2A6519}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{696F6AAE-2D41-48F7-8FCD-E95CFE2A6519}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{A741610F-29B9-4F0E-9A3D-0B3E1318F031}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{A741610F-29B9-4F0E-9A3D-0B3E1318F031}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{A741610F-29B9-4F0E-9A3D-0B3E1318F031}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{A741610F-29B9-4F0E-9A3D-0B3E1318F031}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{3F26CB3D-ECD1-4D50-8AE6-EB6762CBACF6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{3F26CB3D-ECD1-4D50-8AE6-EB6762CBACF6}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{3F26CB3D-ECD1-4D50-8AE6-EB6762CBACF6}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
@ -77,10 +71,10 @@ Global
|
||||
{6BACBAAB-3777-4165-A2F7-7F9B517286B4}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{6BACBAAB-3777-4165-A2F7-7F9B517286B4}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{6BACBAAB-3777-4165-A2F7-7F9B517286B4}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{036F9BD9-308C-4194-AB40-C5952EF0E9F5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{036F9BD9-308C-4194-AB40-C5952EF0E9F5}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{036F9BD9-308C-4194-AB40-C5952EF0E9F5}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{036F9BD9-308C-4194-AB40-C5952EF0E9F5}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{AE22B541-A21E-48F1-9913-C1ACEBF21874}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{AE22B541-A21E-48F1-9913-C1ACEBF21874}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{AE22B541-A21E-48F1-9913-C1ACEBF21874}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{AE22B541-A21E-48F1-9913-C1ACEBF21874}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
@ -88,7 +82,6 @@ Global
|
||||
GlobalSection(NestedProjects) = preSolution
|
||||
{22ED65D3-E2FB-49E4-BDF5-EB2A70774C2E} = {D0066C06-A89A-4E05-80E0-D8232FB0FF3C}
|
||||
{696F6AAE-2D41-48F7-8FCD-E95CFE2A6519} = {D0066C06-A89A-4E05-80E0-D8232FB0FF3C}
|
||||
{A741610F-29B9-4F0E-9A3D-0B3E1318F031} = {D0066C06-A89A-4E05-80E0-D8232FB0FF3C}
|
||||
{3F26CB3D-ECD1-4D50-8AE6-EB6762CBACF6} = {A2CAD164-0816-4D1D-9793-1B1F398C9D29}
|
||||
{E5AE46D9-D809-4E87-8ADD-B1BD28ED60E9} = {A2CAD164-0816-4D1D-9793-1B1F398C9D29}
|
||||
{3F52D1D0-4B1E-4819-9AB3-A770DD5C505D} = {A2CAD164-0816-4D1D-9793-1B1F398C9D29}
|
||||
@ -96,7 +89,7 @@ Global
|
||||
{45FBC25D-9EC5-4C8E-A979-005F04CE76AB} = {A2CAD164-0816-4D1D-9793-1B1F398C9D29}
|
||||
{16AF64F5-6BED-4BD5-AD41-39816AD56769} = {F4C45C48-8011-4782-B0B3-99164D611A6C}
|
||||
{6BACBAAB-3777-4165-A2F7-7F9B517286B4} = {F4C45C48-8011-4782-B0B3-99164D611A6C}
|
||||
{036F9BD9-308C-4194-AB40-C5952EF0E9F5} = {D0066C06-A89A-4E05-80E0-D8232FB0FF3C}
|
||||
{AE22B541-A21E-48F1-9913-C1ACEBF21874} = {A2CAD164-0816-4D1D-9793-1B1F398C9D29}
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {22107F03-013F-4871-AC8E-F082694E2679}
|
||||
|
@ -1,5 +1,4 @@
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace HaoYueNet.ClientNetwork
|
||||
{
|
||||
public static class BaseData
|
||||
@ -8,21 +7,6 @@ namespace HaoYueNet.ClientNetwork
|
||||
/// 心跳包数据
|
||||
/// </summary>
|
||||
public static byte[] HeartbeatData = new byte[5] { 0x05, 0x00, 0x00, 0x00, 0x00 };
|
||||
|
||||
public static void writeInt(byte[] buf, int offset, int value)
|
||||
{
|
||||
buf[offset++] = (byte)(255 & value);
|
||||
buf[offset++] = (byte)(255 & value >> 8);
|
||||
buf[offset++] = (byte)(255 & value >> 16);
|
||||
buf[offset++] = (byte)(255 & value >>> 24);
|
||||
}
|
||||
|
||||
public static void writeUInt16(byte[] buf, int offset, int value)
|
||||
{
|
||||
buf[offset++] = (byte)(255 & value);
|
||||
buf[offset++] = (byte)(255 & value >> 8);
|
||||
}
|
||||
|
||||
public static class HunterNet_Heartbeat
|
||||
{
|
||||
public static void SetDataToSocketAsyncEventArgs(SocketAsyncEventArgs myreadEventArgs)
|
||||
@ -30,171 +14,58 @@ namespace HaoYueNet.ClientNetwork
|
||||
myreadEventArgs.SetBuffer(HeartbeatData, 0, HeartbeatData.Length);
|
||||
}
|
||||
}
|
||||
|
||||
public static class HunterNet_S2C
|
||||
{
|
||||
public static void SetDataToSocketAsyncEventArgs(SocketAsyncEventArgs myreadEventArgs, UInt16 CmdID, UInt16 Error, byte[] AddonBytes_Data)
|
||||
{
|
||||
myreadEventArgs.SetBuffer(CreatePkgData(CmdID, Error, AddonBytes_Data));
|
||||
}
|
||||
|
||||
public static byte[] CreatePkgData(UInt16 CmdID, UInt16 Error, byte[] AddonBytes_Data)
|
||||
{
|
||||
//byte[] AddonBytes_CmdID = BitConverter.GetBytes(CmdID);
|
||||
//byte[] AddonBytes_Error = BitConverter.GetBytes(Error);
|
||||
//int AllLenght = AddonBytes_CmdID.Length + AddonBytes_Error.Length + AddonBytes_Data.Length + 4;
|
||||
//int LastIndex = 0;
|
||||
////包长度
|
||||
//byte[] AddonBytes_Lenght = BitConverter.GetBytes(AllLenght);
|
||||
|
||||
//byte[] BufferData = new byte[AllLenght];
|
||||
////包长度
|
||||
//AddonBytes_Lenght.CopyTo(BufferData, LastIndex);
|
||||
//LastIndex += AddonBytes_Lenght.Length;
|
||||
|
||||
////CMDID
|
||||
//AddonBytes_CmdID.CopyTo(BufferData, LastIndex);
|
||||
//LastIndex += AddonBytes_CmdID.Length;
|
||||
|
||||
////Error
|
||||
//AddonBytes_Error.CopyTo(BufferData, LastIndex);
|
||||
//LastIndex += AddonBytes_Error.Length;
|
||||
|
||||
////DATA
|
||||
//AddonBytes_Data.CopyTo(BufferData, LastIndex);
|
||||
//LastIndex += AddonBytes_Data.Length;
|
||||
//return BufferData;
|
||||
|
||||
////用Buffer.BlockCopy拷贝
|
||||
//byte[] AddonBytes_CmdID = BitConverter.GetBytes(CmdID);
|
||||
//byte[] AddonBytes_Error = BitConverter.GetBytes(Error);
|
||||
//int AllLenght = AddonBytes_CmdID.Length + AddonBytes_Error.Length + AddonBytes_Data.Length + 4;
|
||||
//int LastIndex = 0;
|
||||
////包长度
|
||||
//byte[] AddonBytes_Lenght = BitConverter.GetBytes(AllLenght);
|
||||
|
||||
//byte[] BufferData = new byte[AllLenght];
|
||||
////包长度
|
||||
//Buffer.BlockCopy(AddonBytes_Lenght, 0, BufferData, LastIndex, AddonBytes_Lenght.Length);
|
||||
//LastIndex += AddonBytes_Lenght.Length;
|
||||
|
||||
////CMDID
|
||||
//Buffer.BlockCopy(AddonBytes_CmdID, 0, BufferData, LastIndex, AddonBytes_CmdID.Length);
|
||||
//LastIndex += AddonBytes_CmdID.Length;
|
||||
|
||||
////Error
|
||||
//Buffer.BlockCopy(AddonBytes_Error, 0, BufferData, LastIndex, AddonBytes_Error.Length);
|
||||
//LastIndex += AddonBytes_Error.Length;
|
||||
|
||||
////DATA
|
||||
//Buffer.BlockCopy(AddonBytes_Data, 0, BufferData, LastIndex, AddonBytes_Data.Length);
|
||||
//LastIndex += AddonBytes_Data.Length;
|
||||
|
||||
|
||||
|
||||
//用Buffer.BlockCopy拷贝
|
||||
//包长度
|
||||
int AllLenght = 4 + 2 + 2 + AddonBytes_Data.Length;
|
||||
byte[] BufferData = new byte[AllLenght];
|
||||
|
||||
//包长度
|
||||
writeInt(BufferData, 0, AllLenght);
|
||||
|
||||
Buffer.BlockCopy(BitConverter.GetBytes(AllLenght), 0, BufferData, 0, sizeof(int));
|
||||
//CMDID
|
||||
writeUInt16(BufferData, 4, CmdID);
|
||||
|
||||
//Error
|
||||
writeUInt16(BufferData, 4 + 2, CmdID);
|
||||
|
||||
Buffer.BlockCopy(BitConverter.GetBytes(CmdID), 0, BufferData, 4, sizeof(UInt16));
|
||||
//ErrID
|
||||
Buffer.BlockCopy(BitConverter.GetBytes(Error), 0, BufferData, 4 + 2, sizeof(UInt16));
|
||||
//DATA
|
||||
Buffer.BlockCopy(AddonBytes_Data, 0, BufferData, 4 + 2 + 2, AddonBytes_Data.Length);
|
||||
|
||||
return BufferData;
|
||||
}
|
||||
|
||||
public static void AnalysisPkgData(Span<byte> srcdata, out UInt16 CmdID, out UInt16 Error, out byte[] data)
|
||||
{
|
||||
//CmdID = BitConverter.ToUInt16(srcdata, 0);
|
||||
//Error = BitConverter.ToUInt16(srcdata, 2);
|
||||
//data = new byte[srcdata.Length - 2 - 2];
|
||||
//Array.Copy(srcdata, 4, data, 0, data.Length);
|
||||
|
||||
//CmdID = BitConverter.ToUInt16(srcdata, 0);
|
||||
//Error = BitConverter.ToUInt16(srcdata, 2);
|
||||
//Span<byte> span_srcdata = srcdata;
|
||||
//data = span_srcdata.Slice(2 + 2).ToArray();
|
||||
|
||||
CmdID = BitConverter.ToUInt16(srcdata.Slice(0, 2));
|
||||
Error = BitConverter.ToUInt16(srcdata.Slice(2, 2));
|
||||
data = srcdata.Slice(2 + 2).ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
public static class HunterNet_C2S
|
||||
{
|
||||
public static void SetDataToSocketAsyncEventArgs(SocketAsyncEventArgs myreadEventArgs, UInt16 CmdID, byte[] AddonBytes_Data)
|
||||
{
|
||||
myreadEventArgs.SetBuffer(CreatePkgData(CmdID, AddonBytes_Data));
|
||||
}
|
||||
|
||||
public static byte[] CreatePkgData(UInt16 CmdID, byte[] AddonBytes_Data)
|
||||
{
|
||||
//byte[] AddonBytes_CmdID = BitConverter.GetBytes(CmdID);
|
||||
//int AllLenght = AddonBytes_CmdID.Length + AddonBytes_Data.Length + 4;
|
||||
//int LastIndex = 0;
|
||||
////包长度
|
||||
//byte[] AddonBytes_Lenght = BitConverter.GetBytes(AllLenght);
|
||||
|
||||
//byte[] BufferData = new byte[AllLenght];
|
||||
|
||||
////包长度
|
||||
//AddonBytes_Lenght.CopyTo(BufferData, LastIndex);
|
||||
//LastIndex += AddonBytes_Lenght.Length;
|
||||
|
||||
////CMDID
|
||||
//AddonBytes_CmdID.CopyTo(BufferData, LastIndex);
|
||||
//LastIndex += AddonBytes_CmdID.Length;
|
||||
|
||||
////DATA
|
||||
//AddonBytes_Data.CopyTo(BufferData, LastIndex);
|
||||
//LastIndex += AddonBytes_Data.Length;
|
||||
|
||||
//myreadEventArgs.SetBuffer(BufferData, 0, BufferData.Length);
|
||||
//return BufferData;
|
||||
|
||||
//用Buffer.BlockCopy拷贝
|
||||
|
||||
byte[] AddonBytes_CmdID = BitConverter.GetBytes(CmdID);
|
||||
int AllLenght = AddonBytes_CmdID.Length + AddonBytes_Data.Length + 4;
|
||||
int LastIndex = 0;
|
||||
//包长度
|
||||
byte[] AddonBytes_Lenght = BitConverter.GetBytes(AllLenght);
|
||||
|
||||
byte[] BufferData = new byte[AllLenght];
|
||||
//包长度
|
||||
Buffer.BlockCopy(AddonBytes_Lenght, 0, BufferData, LastIndex, AddonBytes_Lenght.Length);
|
||||
LastIndex += AddonBytes_Lenght.Length;
|
||||
|
||||
Buffer.BlockCopy(AddonBytes_Lenght, 0, BufferData, 0, AddonBytes_Lenght.Length);
|
||||
//CMDID
|
||||
Buffer.BlockCopy(AddonBytes_CmdID, 0, BufferData, LastIndex, AddonBytes_CmdID.Length);
|
||||
LastIndex += AddonBytes_CmdID.Length;
|
||||
|
||||
Buffer.BlockCopy(AddonBytes_CmdID, 0, BufferData, 4, AddonBytes_CmdID.Length);
|
||||
//DATA
|
||||
Buffer.BlockCopy(AddonBytes_Data, 0, BufferData, LastIndex, AddonBytes_Data.Length);
|
||||
LastIndex += AddonBytes_Data.Length;
|
||||
Buffer.BlockCopy(AddonBytes_Data, 0, BufferData, 4 + 2, AddonBytes_Data.Length);
|
||||
return BufferData;
|
||||
}
|
||||
|
||||
public static void AnalysisPkgData(Span<byte> srcdata, out UInt16 CmdID, out byte[] data)
|
||||
{
|
||||
//data = new byte[srcdata.Length - 2];
|
||||
//CmdID = BitConverter.ToUInt16(srcdata, 0);
|
||||
//Array.Copy(srcdata, 2, data, 0, data.Length);
|
||||
|
||||
//CmdID = BitConverter.ToUInt16(srcdata, 0);
|
||||
//Span<byte> span_srcdata = srcdata;
|
||||
//data = span_srcdata.Slice(2).ToArray();
|
||||
|
||||
CmdID = BitConverter.ToUInt16(srcdata.Slice(0, 2));
|
||||
data = srcdata.Slice(2).ToArray();
|
||||
}
|
||||
|
54
NetLib/HaoYueNet.ClientNetwork/IOCPMode/AsyncUserToken.cs
Normal file
54
NetLib/HaoYueNet.ClientNetwork/IOCPMode/AsyncUserToken.cs
Normal file
@ -0,0 +1,54 @@
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace HaoYueNet.ClientNetwork.IOCPMode
|
||||
{
|
||||
public class AsyncUserToken
|
||||
{
|
||||
/// <summary>
|
||||
/// 客户端IP地址
|
||||
/// </summary>
|
||||
public IPAddress IPAddress { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 远程地址
|
||||
/// </summary>
|
||||
public EndPoint Remote { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 通信SOKET
|
||||
/// </summary>
|
||||
public Socket Socket { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 连接时间
|
||||
/// </summary>
|
||||
public DateTime ConnectTime { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 所属用户信息
|
||||
/// </summary>
|
||||
public object UserInfo { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 数据缓存区
|
||||
/// </summary>
|
||||
//public List<byte> Buffer { get; set; }
|
||||
|
||||
public MemoryStream memoryStream { get; set; }
|
||||
|
||||
public AsyncUserToken()
|
||||
{
|
||||
//this.Buffer = new List<byte>();
|
||||
memoryStream = new MemoryStream();
|
||||
}
|
||||
/// <summary>
|
||||
/// 响应倒计时计数
|
||||
/// </summary>
|
||||
public int RevIndex { get; set; } = 0;
|
||||
/// <summary>
|
||||
/// 发送倒计时计数
|
||||
/// </summary>
|
||||
public int SendIndex { get; set; } = 0;
|
||||
}
|
||||
}
|
60
NetLib/HaoYueNet.ClientNetwork/IOCPMode/BufferManager.cs
Normal file
60
NetLib/HaoYueNet.ClientNetwork/IOCPMode/BufferManager.cs
Normal file
@ -0,0 +1,60 @@
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace HaoYueNet.ClientNetwork.IOCPMode
|
||||
{
|
||||
public class BufferManager
|
||||
{
|
||||
int m_numBytes; // the total number of bytes controlled by the buffer pool
|
||||
byte[] m_buffer; // the underlying byte array maintained by the Buffer Manager
|
||||
Stack<int> m_freeIndexPool; //
|
||||
int m_currentIndex;
|
||||
int m_bufferSize;
|
||||
|
||||
public BufferManager(int totalBytes, int bufferSize)
|
||||
{
|
||||
m_numBytes = totalBytes;
|
||||
m_currentIndex = 0;
|
||||
m_bufferSize = bufferSize;
|
||||
m_freeIndexPool = new Stack<int>();
|
||||
}
|
||||
|
||||
// Allocates buffer space used by the buffer pool
|
||||
public void InitBuffer()
|
||||
{
|
||||
// create one big large buffer and divide that
|
||||
// out to each SocketAsyncEventArg object
|
||||
m_buffer = new byte[m_numBytes];
|
||||
}
|
||||
|
||||
// Assigns a buffer from the buffer pool to the
|
||||
// specified SocketAsyncEventArgs object
|
||||
//
|
||||
// <returns>true if the buffer was successfully set, else false</returns>
|
||||
public bool SetBuffer(SocketAsyncEventArgs args)
|
||||
{
|
||||
|
||||
if (m_freeIndexPool.Count > 0)
|
||||
{
|
||||
args.SetBuffer(m_buffer, m_freeIndexPool.Pop(), m_bufferSize);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (m_numBytes - m_bufferSize < m_currentIndex)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
args.SetBuffer(m_buffer, m_currentIndex, m_bufferSize);
|
||||
m_currentIndex += m_bufferSize;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Removes the buffer from a SocketAsyncEventArg object.
|
||||
// This frees the buffer back to the buffer pool
|
||||
public void FreeBuffer(SocketAsyncEventArgs args)
|
||||
{
|
||||
m_freeIndexPool.Push(args.Offset);
|
||||
args.SetBuffer(null, 0, 0);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,8 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace HaoYueNet.ServerNetworkNet4x
|
||||
namespace HaoYueNet.ClientNetwork.IOCPMode
|
||||
{
|
||||
|
||||
public class MemoryStreamPool
|
45
NetLib/HaoYueNet.ClientNetwork/IOCPMode/SocketEventPool.cs
Normal file
45
NetLib/HaoYueNet.ClientNetwork/IOCPMode/SocketEventPool.cs
Normal file
@ -0,0 +1,45 @@
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace HaoYueNet.ClientNetwork.IOCPMode
|
||||
{
|
||||
|
||||
public class SocketEventPool
|
||||
{
|
||||
Stack<SocketAsyncEventArgs> m_pool;
|
||||
|
||||
public SocketEventPool(int capacity)
|
||||
{
|
||||
m_pool = new Stack<SocketAsyncEventArgs>(capacity);
|
||||
}
|
||||
|
||||
public void Push(SocketAsyncEventArgs item)
|
||||
{
|
||||
if (item == null) { throw new ArgumentNullException("Items added to a SocketAsyncEventArgsPool cannot be null"); }
|
||||
lock (m_pool)
|
||||
{
|
||||
m_pool.Push(item);
|
||||
}
|
||||
}
|
||||
|
||||
// Removes a SocketAsyncEventArgs instance from the pool
|
||||
// and returns the object removed from the pool
|
||||
public SocketAsyncEventArgs Pop()
|
||||
{
|
||||
lock (m_pool)
|
||||
{
|
||||
return m_pool.Pop();
|
||||
}
|
||||
}
|
||||
|
||||
// The number of SocketAsyncEventArgs instances in the pool
|
||||
public int Count
|
||||
{
|
||||
get { return m_pool.Count; }
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
m_pool.Clear();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,28 +1,26 @@
|
||||
//using HunterProtobufCore;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Buffers;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
using static HaoYueNet.ServerNetworkNet4x.BaseData;
|
||||
using static HaoYueNet.ClientNetwork.BaseData;
|
||||
|
||||
namespace HaoYueNet.ServerNetworkNet4x
|
||||
namespace HaoYueNet.ClientNetwork.IOCPMode
|
||||
{
|
||||
public class TcpSaeaServer_SourceMode
|
||||
public class TcpSaeaClient
|
||||
{
|
||||
#region 定义属性
|
||||
protected int MaxRevIndexNum = 50;//响应倒计时计数最大值
|
||||
protected int MaxSendIndexNum = 3;//发送倒计时计数最大值
|
||||
protected static int TimerInterval = 3000;//计时器间隔
|
||||
//protected System.Timers.Timer _heartTimer;//心跳包计数器
|
||||
protected System.Timers.Timer _heartTimer;//心跳包计数器
|
||||
public int m_maxConnectNum; //最大连接数
|
||||
public int m_revBufferSize; //最大接收字节数
|
||||
protected BufferManager m_bufferManager;
|
||||
protected const int opsToAlloc = 2;
|
||||
Socket listenSocket; //监听Socket
|
||||
protected SocketEventPool m_Receivepool;
|
||||
protected SocketEventPool m_Sendpool;
|
||||
protected TokenMsgPool_SourceMode msg_pool;
|
||||
protected TokenMsgPool msg_pool;
|
||||
protected int m_clientCount; //连接的客户端数量
|
||||
protected Semaphore m_maxNumberAcceptedClients;//信号量
|
||||
protected Dictionary<Socket, AsyncUserToken> _DictSocketAsyncUserToken = new Dictionary<Socket, AsyncUserToken>();
|
||||
@ -42,7 +40,7 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
/// </summary>
|
||||
/// <param name="token">客户端</param>
|
||||
/// <param name="buff">客户端数据</param>
|
||||
public delegate void OnReceiveDataHandler(AsyncUserToken sk, byte[] data);
|
||||
public delegate void OnReceiveDataHandler(AsyncUserToken sk, int CMDID, int ErrID, byte[] data);
|
||||
/// <summary>
|
||||
/// 断开连接
|
||||
/// </summary>
|
||||
@ -79,7 +77,7 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
/// </summary>
|
||||
/// <param name="numConnections">最大连接数</param>
|
||||
/// <param name="receiveBufferSize">缓存区大小</param>
|
||||
public TcpSaeaServer_SourceMode(int numConnections, int receiveBufferSize)
|
||||
public TcpSaeaClient(int numConnections, int receiveBufferSize)
|
||||
{
|
||||
m_clientCount = 0;
|
||||
m_maxConnectNum = numConnections;
|
||||
@ -91,7 +89,7 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
m_Receivepool = new SocketEventPool(numConnections);
|
||||
m_Sendpool = new SocketEventPool(numConnections);
|
||||
|
||||
msg_pool = new TokenMsgPool_SourceMode(numConnections);
|
||||
msg_pool = new TokenMsgPool(numConnections);
|
||||
|
||||
m_maxNumberAcceptedClients = new Semaphore(numConnections, numConnections);
|
||||
}
|
||||
@ -139,32 +137,18 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
/// <param name="localEndPoint"></param>
|
||||
/// <param name="bReuseAddress">是否端口重用</param>
|
||||
/// <returns></returns>
|
||||
public bool Start(IPEndPoint localEndPoint, bool bReuseAddress = false)
|
||||
public bool Start()
|
||||
{
|
||||
try
|
||||
{
|
||||
ClearUserToken();
|
||||
listenSocket = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
|
||||
|
||||
if (bReuseAddress)
|
||||
{
|
||||
listenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
OutNetLog("监听:" + listenSocket.LocalEndPoint.ToString());
|
||||
|
||||
//_heartTimer = new System.Timers.Timer();
|
||||
//_heartTimer.Interval = TimerInterval;
|
||||
//_heartTimer.Elapsed += CheckUpdatetimer_Elapsed;
|
||||
//_heartTimer.AutoReset = true;
|
||||
//_heartTimer.Enabled = true;
|
||||
//OutNetLog("开启定时心跳包");
|
||||
_heartTimer = new System.Timers.Timer();
|
||||
_heartTimer.Interval = TimerInterval;
|
||||
_heartTimer.Elapsed += CheckUpdatetimer_Elapsed;
|
||||
_heartTimer.AutoReset = true;
|
||||
_heartTimer.Enabled = true;
|
||||
OutNetLog("开启定时心跳包");
|
||||
|
||||
return true;
|
||||
}
|
||||
@ -173,6 +157,7 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 停止服务
|
||||
/// </summary>
|
||||
@ -188,11 +173,20 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
}
|
||||
try
|
||||
{
|
||||
listenSocket.Shutdown(SocketShutdown.Both);
|
||||
for (int i = 0; i < m_clients.Count; i++)
|
||||
{
|
||||
m_clients[i].Socket.Shutdown(SocketShutdown.Both);
|
||||
}
|
||||
//listenSocket.Shutdown(SocketShutdown.Both);
|
||||
|
||||
for (int i = 0; i < m_clients.Count; i++)
|
||||
{
|
||||
m_clients[i].Socket.Close();
|
||||
}
|
||||
}
|
||||
catch (Exception) { }
|
||||
|
||||
listenSocket.Close();
|
||||
//listenSocket.Close();
|
||||
int c_count = m_clients.Count;
|
||||
ClearUserToken();
|
||||
|
||||
@ -201,7 +195,7 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
}
|
||||
public void CloseClient(AsyncUserToken token)
|
||||
{
|
||||
try {token.Socket.Shutdown(SocketShutdown.Both);}
|
||||
try { token.Socket.Shutdown(SocketShutdown.Both); }
|
||||
catch (Exception) { }
|
||||
}
|
||||
/// <summary>
|
||||
@ -233,7 +227,11 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
#region Token管理
|
||||
public AsyncUserToken GetAsyncUserTokenForSocket(Socket sk)
|
||||
{
|
||||
return _DictSocketAsyncUserToken.ContainsKey(sk) ? _DictSocketAsyncUserToken[sk] : null;
|
||||
AsyncUserToken result;
|
||||
if (_DictSocketAsyncUserToken.TryGetValue(sk, out result))
|
||||
return result;
|
||||
return null;
|
||||
//return _DictSocketAsyncUserToken.ContainsKey(sk) ? _DictSocketAsyncUserToken[sk] : null;
|
||||
}
|
||||
void AddUserToken(AsyncUserToken userToken)
|
||||
{
|
||||
@ -286,46 +284,42 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 监听IOCP循环
|
||||
/// <summary>
|
||||
/// 开始接受客户端的连接请求的操作
|
||||
/// </summary>
|
||||
/// <param name="acceptEventArg">在服务器的侦听套接字上发出接受操作时要使用的上下文对象</param>
|
||||
public void StartAccept(SocketAsyncEventArgs acceptEventArg)
|
||||
|
||||
|
||||
#region 连接
|
||||
public void StartConnect(string ip, int port, Socket socket, SocketAsyncEventArgs connectEventArg = null)
|
||||
{
|
||||
if (acceptEventArg == null)
|
||||
if (connectEventArg == null)
|
||||
{
|
||||
acceptEventArg = new SocketAsyncEventArgs();
|
||||
acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(AcceptEventArg_Completed);
|
||||
connectEventArg = new SocketAsyncEventArgs();
|
||||
connectEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed);
|
||||
}
|
||||
else
|
||||
{
|
||||
// socket must be cleared since the context object is being reused
|
||||
acceptEventArg.AcceptSocket = null;
|
||||
connectEventArg.AcceptSocket = null;
|
||||
//TODO ??
|
||||
//这里其实AcceptSocket是服务端用的,非监听的客户端用,本来就为空,清不清理没什么卵用,但是connectEventArg.ConnectSocket是只读的的
|
||||
}
|
||||
|
||||
connectEventArg.RemoteEndPoint = new DnsEndPoint(ip, port);
|
||||
|
||||
m_maxNumberAcceptedClients.WaitOne();
|
||||
if (!listenSocket.AcceptAsync(acceptEventArg))
|
||||
|
||||
if (!socket.ConnectAsync(connectEventArg))
|
||||
{
|
||||
ProcessAccept(acceptEventArg);
|
||||
ProcessConnect(connectEventArg);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 此方法是与Socket关联的回调方法。AcceptAsync操作,并在接受操作完成时调用
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
void AcceptEventArg_Completed(object sender, SocketAsyncEventArgs e)
|
||||
{
|
||||
ProcessAccept(e);
|
||||
}
|
||||
private void ProcessAccept(SocketAsyncEventArgs e)
|
||||
|
||||
private void ProcessConnect(SocketAsyncEventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
Interlocked.Increment(ref m_clientCount);
|
||||
|
||||
//确保监听结束时,有连接才抛给数据接收
|
||||
if (e.AcceptSocket.RemoteEndPoint != null)
|
||||
if (e.ConnectSocket.RemoteEndPoint != null)
|
||||
{
|
||||
// Get the socket for the accepted client connection and put it into the
|
||||
//ReadEventArg object user token
|
||||
@ -336,11 +330,10 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
readEventArgs.UserToken = new AsyncUserToken();
|
||||
|
||||
userToken = (AsyncUserToken)readEventArgs.UserToken;
|
||||
userToken.Socket = e.AcceptSocket;
|
||||
userToken.Socket = e.ConnectSocket;
|
||||
userToken.ConnectTime = DateTime.Now;
|
||||
userToken.Remote = e.AcceptSocket.RemoteEndPoint;
|
||||
userToken.IPAddress = ((IPEndPoint)(e.AcceptSocket.RemoteEndPoint)).Address;
|
||||
|
||||
userToken.Remote = e.ConnectSocket.RemoteEndPoint;
|
||||
userToken.IPAddress = ((IPEndPoint)e.ConnectSocket.RemoteEndPoint).Address;
|
||||
|
||||
userToken.RevIndex = MaxRevIndexNum;
|
||||
userToken.SendIndex = MaxSendIndexNum;
|
||||
@ -348,7 +341,7 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
AddUserToken(userToken);
|
||||
|
||||
OnClientNumberChange?.Invoke(1, userToken);
|
||||
if (!e.AcceptSocket.ReceiveAsync(readEventArgs))
|
||||
if (!e.ConnectSocket.ReceiveAsync(readEventArgs))
|
||||
{
|
||||
ProcessReceive(readEventArgs);
|
||||
}
|
||||
@ -361,7 +354,7 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
|
||||
// Accept the next connection request
|
||||
if (e.SocketError == SocketError.OperationAborted) return;
|
||||
StartAccept(e);
|
||||
//StartAccept(e);
|
||||
}
|
||||
#endregion
|
||||
|
||||
@ -375,47 +368,67 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
{
|
||||
try
|
||||
{
|
||||
// check if the remote host closed the connection
|
||||
AsyncUserToken token = (AsyncUserToken)e.UserToken;
|
||||
if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
|
||||
{
|
||||
//读取数据
|
||||
//byte[] data = new byte[e.BytesTransferred];
|
||||
//Array.Copy(e.Buffer, e.Offset, data, 0, e.BytesTransferred);
|
||||
//lock (token.Buffer)
|
||||
lock(token.memoryStream)
|
||||
lock (token.memoryStream)
|
||||
{
|
||||
//token.Buffer.AddRange(data);
|
||||
token.memoryStream.Write(e.Buffer, e.Offset, e.BytesTransferred);
|
||||
do
|
||||
{
|
||||
if (token.memoryStream.Length < 4) break;//包头不完整,继续接收
|
||||
long FristBeginPos = token.memoryStream.Position;
|
||||
|
||||
//DataCallBackReady(token, data);
|
||||
////从数据池中移除这组数据
|
||||
//lock (token.Buffer)
|
||||
//{
|
||||
// token.Buffer.Clear();
|
||||
//}
|
||||
//从Byte池申请
|
||||
byte[] lenBytes = ArrayPool<byte>.Shared.Rent(4);
|
||||
|
||||
DataCallBackReady(token, token.memoryStream.ToArray());
|
||||
//流复用的方式 不用重新new申请
|
||||
token.memoryStream.Position = 0;
|
||||
token.memoryStream.SetLength(0);
|
||||
token.memoryStream.Seek(0, SeekOrigin.Begin);
|
||||
token.memoryStream.Read(lenBytes, 0, 4);
|
||||
int packageLen = BitConverter.ToInt32(lenBytes, 0) - 4;
|
||||
|
||||
//这里API处理完后,并没有返回结果,当然结果是要返回的,却不是在这里, 这里的代码只管接收.
|
||||
//若要返回结果,可在API处理中调用此类对象的SendMessage方法,统一打包发送.不要被微软的示例给迷惑了.
|
||||
} while (token.memoryStream.Length > 0);
|
||||
//} while (token.Buffer.Count > 4);
|
||||
}
|
||||
//归还byte[]
|
||||
ArrayPool<byte>.Shared.Return(lenBytes);
|
||||
|
||||
//继续接收. 为什么要这么写,请看Socket.ReceiveAsync方法的说明
|
||||
if (!token.Socket.ReceiveAsync(e))
|
||||
if (packageLen > token.memoryStream.Length - 4)
|
||||
{
|
||||
this.ProcessReceive(e);
|
||||
token.memoryStream.Seek(FristBeginPos, SeekOrigin.Begin);
|
||||
break;//长度不够时,退出循环,让程序继续接收
|
||||
}
|
||||
|
||||
//申请byte池 一定要记得回收!!
|
||||
byte[] rev_fromArrayPool = ArrayPool<byte>.Shared.Rent(packageLen);
|
||||
|
||||
token.memoryStream.Seek(4, SeekOrigin.Begin);
|
||||
token.memoryStream.Read(rev_fromArrayPool, 0, packageLen);
|
||||
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);
|
||||
}
|
||||
|
||||
//用Span内存切片,因为来自ArrayPool的byte长度,可能大于本身申请的长度
|
||||
Span<byte> rev_span = rev_fromArrayPool;
|
||||
rev_span = rev_span.Slice(0, packageLen);
|
||||
DataCallBackReady(token, rev_span);
|
||||
|
||||
//回收(这里依赖DataCallBackReady中,有一次数据拷贝,这个后续还要进一步精进性能优化,否则不能在这里回收,否则影响业务层)
|
||||
ArrayPool<byte>.Shared.Return(rev_fromArrayPool);
|
||||
} while (token.memoryStream.Length > 4);
|
||||
}
|
||||
|
||||
//如果返回为False则代表此刻已经完成,不必等待完成端口回调,则直接调用ProcessReceive
|
||||
if (!token.Socket.ReceiveAsync(e))
|
||||
this.ProcessReceive(e);
|
||||
}
|
||||
else
|
||||
{
|
||||
//清理数据
|
||||
token.memoryStream.SetLength(0);
|
||||
token.memoryStream.Seek(0, SeekOrigin.Begin);
|
||||
CloseClientSocket(e);
|
||||
}
|
||||
}
|
||||
@ -444,6 +457,9 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
|
||||
switch (e.LastOperation)
|
||||
{
|
||||
case SocketAsyncOperation.Connect:
|
||||
ProcessConnect(e);
|
||||
break;
|
||||
case SocketAsyncOperation.Receive:
|
||||
ProcessReceive(e);
|
||||
break;
|
||||
@ -463,11 +479,12 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
/// </summary>
|
||||
/// <param name="CMDID"></param>
|
||||
/// <param name="data">序列化之后的数据</param>
|
||||
public void SendToSocket(Socket sk, byte[] data)
|
||||
public void SendToSocket(Socket sk, int CMDID, byte[] data)
|
||||
{
|
||||
AsyncUserToken token = GetAsyncUserTokenForSocket(sk);
|
||||
SendWithIndex(token, data);
|
||||
SendWithIndex(token, (ushort)CMDID, data);
|
||||
}
|
||||
|
||||
void SendForMsgPool()
|
||||
{
|
||||
//if (flag_SendForMsgPool) return;
|
||||
@ -481,7 +498,7 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
{
|
||||
try
|
||||
{
|
||||
TokenWithMsg_SourceMode msg = msg_pool.Dequeue();
|
||||
TokenWithMsg msg = msg_pool.Dequeue();
|
||||
//OutNetLog("从信息池取出发送");
|
||||
//是心跳包
|
||||
if (msg.bHeartbeat)
|
||||
@ -490,7 +507,7 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
}
|
||||
else
|
||||
{
|
||||
SendMessage(msg.token,msg.data);
|
||||
SendMessage(msg.token, msg.CMDID, msg.data);
|
||||
}
|
||||
msg = null;
|
||||
}
|
||||
@ -523,7 +540,9 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
{
|
||||
SocketAsyncEventArgs myreadEventArgs = m_Sendpool.Pop();
|
||||
myreadEventArgs.UserToken = token;
|
||||
myreadEventArgs.AcceptSocket = token.Socket;
|
||||
//TODO ????客户端用这里是否应该直接就不设置
|
||||
//myreadEventArgs.AcceptSocket = token.Socket;
|
||||
|
||||
//直接写入SocketAsyncEventArgs的Buff
|
||||
HunterNet_Heartbeat.SetDataToSocketAsyncEventArgs(myreadEventArgs);
|
||||
|
||||
@ -537,7 +556,7 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
else
|
||||
{
|
||||
//先压入队列,等待m_Sendpool回收
|
||||
msg_pool.Enqueue(new TokenWithMsg_SourceMode() { token = token, bHeartbeat = true });
|
||||
msg_pool.Enqueue(new TokenWithMsg() { token = token, bHeartbeat = true });
|
||||
//OutNetLog("!!!!压入消息发送队列MSG_Pool");
|
||||
return;
|
||||
}
|
||||
@ -552,12 +571,12 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
/// 发送数据并计数
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
void SendWithIndex(AsyncUserToken token,byte[] data)
|
||||
void SendWithIndex(AsyncUserToken token, ushort CmdID, byte[] data)
|
||||
{
|
||||
try
|
||||
{
|
||||
//发送数据
|
||||
SendMessage(token, data);
|
||||
SendMessage(token, CmdID, data);
|
||||
token.SendIndex = MaxSendIndexNum;
|
||||
}
|
||||
catch
|
||||
@ -566,7 +585,7 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
}
|
||||
}
|
||||
|
||||
void SendMessage(AsyncUserToken token, byte[] data)
|
||||
void SendMessage(AsyncUserToken token, ushort CmdID, byte[] data)
|
||||
{
|
||||
if (token == null || token.Socket == null || !token.Socket.Connected)
|
||||
return;
|
||||
@ -577,7 +596,9 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
SocketAsyncEventArgs myreadEventArgs = m_Sendpool.Pop();
|
||||
myreadEventArgs.UserToken = token;
|
||||
myreadEventArgs.AcceptSocket = token.Socket;
|
||||
myreadEventArgs.SetBuffer(data, 0, data.Length); //将数据放置进去.
|
||||
//myreadEventArgs.SetBuffer(message, 0, message.Length); //将数据放置进去.
|
||||
//更换为CMDID和Data直接写入SocketAsyncEventArgs的Buff
|
||||
HunterNet_C2S.SetDataToSocketAsyncEventArgs(myreadEventArgs, CmdID, data);
|
||||
|
||||
//若不需要等待
|
||||
if (!token.Socket.SendAsync(myreadEventArgs))
|
||||
@ -589,7 +610,7 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
else
|
||||
{
|
||||
//先压入队列,等待m_Sendpool回收
|
||||
msg_pool.Enqueue(new TokenWithMsg_SourceMode() { token = token, data = data ,bHeartbeat = false});
|
||||
msg_pool.Enqueue(new TokenWithMsg() { token = token, CMDID = CmdID, data = data });
|
||||
//OutNetLog("!!!!压入消息发送队列MSG_Pool");
|
||||
return;
|
||||
}
|
||||
@ -602,21 +623,30 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
#endregion
|
||||
|
||||
#region 处理前预备
|
||||
private void DataCallBackReady(AsyncUserToken sk, byte[] data)
|
||||
private void DataCallBackReady(AsyncUserToken sk, Span<byte> data)
|
||||
{
|
||||
//增加接收计数
|
||||
sk.RevIndex = MaxRevIndexNum;
|
||||
|
||||
if (data.Length == 1 && data[0] == 0x00)//心跳包
|
||||
{
|
||||
//OutNetLog("收到心跳包");
|
||||
//无处理
|
||||
}
|
||||
else
|
||||
{
|
||||
try
|
||||
{
|
||||
//将数据包交给后台处理,这里你也可以新开个线程来处理.加快速度.
|
||||
OnReceive?.Invoke(sk, data);
|
||||
HunterNet_S2C.AnalysisPkgData(data, out ushort CmdID, out ushort Error, out byte[] resultdata);
|
||||
OnReceive?.Invoke(sk, CmdID, Error, resultdata);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
OutNetLog("数据解析错误");
|
||||
}
|
||||
}
|
||||
}
|
||||
private void OutNetLog(string msg)
|
||||
{
|
||||
OnNetLog?.Invoke(msg);
|
||||
@ -624,7 +654,6 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
#endregion
|
||||
|
||||
#region 心跳包
|
||||
/*
|
||||
/// <summary>
|
||||
/// 发送心跳包
|
||||
/// </summary>
|
||||
@ -673,7 +702,6 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
#endregion
|
||||
}
|
||||
}
|
@ -4,13 +4,13 @@ using System.Linq;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
|
||||
namespace HaoYueNet.ServerNetworkNet4x
|
||||
namespace HaoYueNet.ClientNetwork.IOCPMode
|
||||
{
|
||||
public class TokenWithMsg
|
||||
{
|
||||
public AsyncUserToken token;
|
||||
public UInt16 CMDID;
|
||||
public UInt16 Error;
|
||||
public ushort CMDID;
|
||||
//public UInt16 Error;
|
||||
public byte[] data;
|
||||
public bool bHeartbeat;
|
||||
}
|
@ -9,7 +9,6 @@ namespace HaoYueNet.ClientNetwork
|
||||
{
|
||||
private Socket client;
|
||||
|
||||
|
||||
////响应倒计时计数最大值
|
||||
//private static int MaxRevIndexNum = 6;
|
||||
|
||||
@ -36,7 +35,7 @@ namespace HaoYueNet.ClientNetwork
|
||||
public static int LastConnectPort;
|
||||
public bool bDetailedLog = false;
|
||||
|
||||
public bool Init(string IP, int port,bool isHadDetailedLog = true, bool bBindReuseAddress = false,int bBindport = 0)
|
||||
public bool Init(string IP, int port,bool isHadDetailedLog = true, bool bBindReuseAddress = false,int bBindport = 0,AddressFamily addressFamily = AddressFamily.InterNetwork)
|
||||
{
|
||||
LogOut("==>初始化网络核心");
|
||||
|
||||
@ -44,7 +43,7 @@ namespace HaoYueNet.ClientNetwork
|
||||
RevIndex = MaxRevIndexNum;
|
||||
SendIndex = MaxSendIndexNum;
|
||||
|
||||
client = new Socket(SocketType.Stream, ProtocolType.Tcp);
|
||||
client = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp);
|
||||
if (bBindReuseAddress)
|
||||
{
|
||||
client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
|
||||
@ -157,26 +156,6 @@ namespace HaoYueNet.ClientNetwork
|
||||
}
|
||||
}
|
||||
|
||||
////拼接头长度
|
||||
//private byte[] SendDataWithHead(byte[] message)
|
||||
//{
|
||||
|
||||
// MemoryStream memoryStream = new MemoryStream();//创建一个内存流
|
||||
|
||||
// byte[] BagHead = BitConverter.GetBytes(message.Length + 4);//往字节数组中写入包头(包头自身的长度和消息体的长度)的长度
|
||||
|
||||
// memoryStream.Write(BagHead, 0, BagHead.Length);//将包头写入内存流
|
||||
|
||||
// memoryStream.Write(message, 0, message.Length);//将消息体写入内存流
|
||||
|
||||
// byte[] HeadAndBody = memoryStream.ToArray();//将内存流中的数据写入字节数组
|
||||
|
||||
// memoryStream.Close();//关闭内存
|
||||
// memoryStream.Dispose();//释放资源
|
||||
|
||||
// return HeadAndBody;
|
||||
//}
|
||||
|
||||
/// <summary>
|
||||
/// 供外部调用 发送消息
|
||||
/// </summary>
|
||||
@ -184,13 +163,6 @@ namespace HaoYueNet.ClientNetwork
|
||||
/// <param name="data">序列化之后的数据</param>
|
||||
public void SendToServer(int CMDID,byte[] data)
|
||||
{
|
||||
//LogOut("准备数据 CMDID=> "+CMDID);
|
||||
/*
|
||||
HunterNet_C2S _c2sdata = new HunterNet_C2S();
|
||||
_c2sdata.HunterNetCoreCmdID = CMDID;
|
||||
_c2sdata.HunterNetCoreData = ByteString.CopyFrom(data);
|
||||
byte[] _finaldata = Serizlize(_c2sdata);
|
||||
*/
|
||||
byte[] _finaldata = HunterNet_C2S.CreatePkgData((ushort)CMDID, data);
|
||||
SendToSocket(_finaldata);
|
||||
}
|
||||
@ -247,46 +219,45 @@ namespace HaoYueNet.ClientNetwork
|
||||
return;
|
||||
}
|
||||
|
||||
/*
|
||||
HunterNet_S2C _c2s = DeSerizlize<HunterNet_S2C>(data);
|
||||
|
||||
OnReceiveData(_c2s.HunterNetCoreCmdID, _c2s.HunterNetCoreERRORCode, _c2s.HunterNetCoreData.ToArray());
|
||||
*/
|
||||
|
||||
HunterNet_S2C.AnalysisPkgData(data, out ushort CmdID, out ushort Error, out byte[] resultdata);
|
||||
OnReceiveData(CmdID, Error, resultdata);
|
||||
}
|
||||
|
||||
|
||||
MemoryStream memoryStream = new MemoryStream();//开辟一个内存流
|
||||
MemoryStream reciveMemoryStream = new MemoryStream();//开辟一个反复使用的内存流
|
||||
byte[] reciveBuffer = new byte[1024 * 1024 * 2];//开辟一个反复使用的byte[]
|
||||
private void Recive(object o)
|
||||
{
|
||||
var client = o as Socket;
|
||||
//MemoryStream memoryStream = new MemoryStream();//开辟一个内存流
|
||||
|
||||
while (true)
|
||||
{
|
||||
byte[] buffer = new byte[1024 * 1024 * 2];
|
||||
int effective=0;
|
||||
int effective = 0;
|
||||
try
|
||||
{
|
||||
effective = client.Receive(buffer);
|
||||
if (effective == 0)
|
||||
effective = client.Receive(reciveBuffer);
|
||||
if (effective == 0)//为0表示已经断开连接
|
||||
{
|
||||
continue;
|
||||
//清理数据
|
||||
reciveMemoryStream.SetLength(0);
|
||||
reciveMemoryStream.Seek(0, SeekOrigin.Begin);
|
||||
//远程主机强迫关闭了一个现有的连接
|
||||
OnCloseReady();
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch(Exception ex)
|
||||
{
|
||||
//清理数据
|
||||
reciveMemoryStream.SetLength(0);
|
||||
reciveMemoryStream.Seek(0, SeekOrigin.Begin);
|
||||
|
||||
//远程主机强迫关闭了一个现有的连接
|
||||
OnCloseReady();
|
||||
return;
|
||||
//断开连接
|
||||
}
|
||||
|
||||
|
||||
memoryStream.Write(buffer, 0, effective);//将接受到的数据写入内存流中
|
||||
byte[] getData = memoryStream.ToArray();//将内存流中的消息体写入字节数组
|
||||
reciveMemoryStream.Write(reciveBuffer, 0, effective);//将接受到的数据写入内存流中
|
||||
byte[] getData = reciveMemoryStream.ToArray();//将内存流中的消息体写入字节数组
|
||||
int StartIndex = 0;//设置一个读取数据的起始下标
|
||||
|
||||
while (true)
|
||||
@ -307,41 +278,25 @@ namespace HaoYueNet.ClientNetwork
|
||||
//↓↓↓↓↓↓↓↓ ↓↓↓
|
||||
if (getData.Length - StartIndex < HeadLength || HeadLength == -1)
|
||||
{
|
||||
/* 一种清空流的方式
|
||||
memoryStream.Close();//关闭内存流
|
||||
memoryStream.Dispose();//释放内存资源
|
||||
memoryStream = new MemoryStream();//创建新的内存流
|
||||
*/
|
||||
|
||||
//流复用的方式 不用重新new申请
|
||||
memoryStream.Position = 0;
|
||||
memoryStream.SetLength(0);
|
||||
reciveMemoryStream.Position = 0;
|
||||
reciveMemoryStream.SetLength(0);
|
||||
|
||||
memoryStream.Write(getData, StartIndex, getData.Length - StartIndex);//从新将接受的消息写入内存流
|
||||
reciveMemoryStream.Write(getData, StartIndex, getData.Length - StartIndex);//从新将接受的消息写入内存流
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
//把头去掉,就可以吃了,蛋白质是牛肉的六倍
|
||||
//DataCallBackReady(getData.Skip(StartIndex+4).Take(HeadLength-4).ToArray());
|
||||
|
||||
int CoreLenght = HeadLength - 4;
|
||||
|
||||
//改为Array.Copy 提升效率
|
||||
//byte[] retData = new byte[CoreLenght];
|
||||
//Array.Copy(getData, StartIndex + 4, retData, 0, CoreLenght);
|
||||
//DataCallBackReady(retData);
|
||||
|
||||
//用Span
|
||||
Span<byte> getData_span = getData;
|
||||
getData_span = getData_span.Slice(StartIndex + 4,CoreLenght);
|
||||
getData_span = getData_span.Slice(StartIndex + 4, CoreLenght);
|
||||
DataCallBackReady(getData_span.ToArray());
|
||||
|
||||
StartIndex += HeadLength;//当读取一条完整的数据后,读取数据的起始下标应为当前接受到的消息体的长度(当前数据的尾部或下一条消息的首部)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@ -370,7 +325,6 @@ namespace HaoYueNet.ClientNetwork
|
||||
|
||||
public void LogOut(string Msg)
|
||||
{
|
||||
//Console.WriteLine(Msg);
|
||||
OnLogOut?.Invoke(Msg);
|
||||
}
|
||||
|
||||
|
@ -24,15 +24,13 @@ namespace HaoYueNet.ClientNetwork
|
||||
|
||||
private System.Timers.Timer _heartTimer;
|
||||
|
||||
public void Init(bool bBindReuseAddress = false,int bBindport = 0)
|
||||
public void Init(bool bBindReuseAddress = false,int bBindport = 0, AddressFamily addressFamily = AddressFamily.InterNetwork)
|
||||
{
|
||||
|
||||
LogOut("==>初始化网络核心");
|
||||
|
||||
RevIndex = MaxRevIndexNum;
|
||||
SendIndex = MaxSendIndexNum;
|
||||
|
||||
client = new Socket(SocketType.Stream, ProtocolType.Tcp);
|
||||
client = new Socket(addressFamily,SocketType.Stream, ProtocolType.Tcp);
|
||||
if (bBindReuseAddress)
|
||||
{
|
||||
client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
|
||||
@ -124,26 +122,6 @@ namespace HaoYueNet.ClientNetwork
|
||||
client.Send(data);
|
||||
}
|
||||
|
||||
////拼接头长度
|
||||
//private byte[] SendDataWithHead(byte[] message)
|
||||
//{
|
||||
|
||||
// MemoryStream memoryStream = new MemoryStream();//创建一个内存流
|
||||
|
||||
// byte[] BagHead = BitConverter.GetBytes(message.Length + 4);//往字节数组中写入包头(包头自身的长度和消息体的长度)的长度
|
||||
|
||||
// memoryStream.Write(BagHead, 0, BagHead.Length);//将包头写入内存流
|
||||
|
||||
// memoryStream.Write(message, 0, message.Length);//将消息体写入内存流
|
||||
|
||||
// byte[] HeadAndBody = memoryStream.ToArray();//将内存流中的数据写入字节数组
|
||||
|
||||
// memoryStream.Close();//关闭内存
|
||||
// memoryStream.Dispose();//释放资源
|
||||
|
||||
// return HeadAndBody;
|
||||
//}
|
||||
|
||||
/// <summary>
|
||||
/// 供外部调用 发送消息
|
||||
/// </summary>
|
||||
@ -152,13 +130,6 @@ namespace HaoYueNet.ClientNetwork
|
||||
/// <param name="data"></param>
|
||||
public void SendToSocket(int CMDID, int ERRCODE, byte[] data)
|
||||
{
|
||||
//LogOut("准备数据 CMDID=> "+CMDID);
|
||||
/*HunterNet_S2C _s2sdata = new HunterNet_S2C();
|
||||
_s2sdata.HunterNetCoreCmdID = CMDID;
|
||||
_s2sdata.HunterNetCoreERRORCode = ERRCODE;
|
||||
_s2sdata.HunterNetCoreData = ByteString.CopyFrom(data);
|
||||
byte[] _finaldata = Serizlize(_s2sdata);*/
|
||||
|
||||
byte[] _finaldata = HunterNet_S2C.CreatePkgData((ushort)CMDID, (ushort)ERRCODE, data);
|
||||
SendToSocket(_finaldata);
|
||||
}
|
||||
@ -182,24 +153,6 @@ namespace HaoYueNet.ClientNetwork
|
||||
/// </summary>
|
||||
public event delegate_str OnLogOut;
|
||||
|
||||
///// <summary>
|
||||
///// 用于调用者回调的虚函数
|
||||
///// </summary>
|
||||
///// <param name="data"></param>
|
||||
//public virtual void DataCallBack(int CMDID,int ERRCODE,byte[] data)
|
||||
//{
|
||||
|
||||
//}
|
||||
|
||||
///// <summary>
|
||||
///// 断开连接
|
||||
///// </summary>
|
||||
///// <param name="sk"></param>
|
||||
//public virtual void OnClose()
|
||||
//{
|
||||
|
||||
//}
|
||||
|
||||
/// <summary>
|
||||
/// 做好处理的连接管理
|
||||
/// </summary>
|
||||
@ -236,49 +189,49 @@ namespace HaoYueNet.ClientNetwork
|
||||
return;
|
||||
}
|
||||
|
||||
/*
|
||||
HunterNet_S2C _c2s = DeSerizlize<HunterNet_S2C>(data);
|
||||
OnDataCallBack(_c2s.HunterNetCoreCmdID, _c2s.HunterNetCoreERRORCode, _c2s.HunterNetCoreData.ToArray());
|
||||
*/
|
||||
HunterNet_S2C.AnalysisPkgData(data, out ushort CmdID, out ushort Error, out byte[] resultdata);
|
||||
OnDataCallBack(CmdID, Error, resultdata);
|
||||
}
|
||||
|
||||
MemoryStream memoryStream = new MemoryStream();//开辟一个内存流
|
||||
MemoryStream reciveMemoryStream = new MemoryStream();//开辟一个反复使用的内存流
|
||||
byte[] reciveBuffer = new byte[1024 * 1024 * 2];//开辟一个反复使用的byte[]
|
||||
private void Recive(object o)
|
||||
{
|
||||
var client = o as Socket;
|
||||
//MemoryStream memoryStream = new MemoryStream();//开辟一个内存流
|
||||
|
||||
while (true)
|
||||
{
|
||||
byte[] buffer = new byte[1024 * 1024 * 2];
|
||||
int effective=0;
|
||||
int effective = 0;
|
||||
try
|
||||
{
|
||||
effective = client.Receive(buffer);
|
||||
if (effective == 0)
|
||||
effective = client.Receive(reciveBuffer);
|
||||
if (effective == 0)//为0表示已经断开连接
|
||||
{
|
||||
continue;
|
||||
//清理数据
|
||||
reciveMemoryStream.SetLength(0);
|
||||
reciveMemoryStream.Seek(0, SeekOrigin.Begin);
|
||||
//远程主机强迫关闭了一个现有的连接
|
||||
OnCloseReady();
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch(Exception ex)
|
||||
catch (Exception ex)
|
||||
{
|
||||
//清理数据
|
||||
reciveMemoryStream.SetLength(0);
|
||||
reciveMemoryStream.Seek(0, SeekOrigin.Begin);
|
||||
|
||||
//远程主机强迫关闭了一个现有的连接
|
||||
OnCloseReady();
|
||||
return;
|
||||
//断开连接
|
||||
}
|
||||
|
||||
|
||||
memoryStream.Write(buffer, 0, effective);//将接受到的数据写入内存流中
|
||||
byte[] getData = memoryStream.ToArray();//将内存流中的消息体写入字节数组
|
||||
reciveMemoryStream.Write(reciveBuffer, 0, effective);//将接受到的数据写入内存流中
|
||||
byte[] getData = reciveMemoryStream.ToArray();//将内存流中的消息体写入字节数组
|
||||
int StartIndex = 0;//设置一个读取数据的起始下标
|
||||
|
||||
while (true)
|
||||
{
|
||||
|
||||
|
||||
if (effective > 0)//如果接受到的消息不为0(不为空)
|
||||
{
|
||||
int HeadLength = 0;//包头长度(包头+包体)
|
||||
@ -295,29 +248,16 @@ namespace HaoYueNet.ClientNetwork
|
||||
//↓↓↓↓↓↓↓↓ ↓↓↓
|
||||
if (getData.Length - StartIndex < HeadLength || HeadLength == -1)
|
||||
{
|
||||
/* 一种清空流的方式
|
||||
memoryStream.Close();//关闭内存流
|
||||
memoryStream.Dispose();//释放内存资源
|
||||
memoryStream = new MemoryStream();//创建新的内存流
|
||||
*/
|
||||
|
||||
//流复用的方式 不用重新new申请
|
||||
memoryStream.Position = 0;
|
||||
memoryStream.SetLength(0);
|
||||
reciveMemoryStream.Position = 0;
|
||||
reciveMemoryStream.SetLength(0);
|
||||
|
||||
memoryStream.Write(getData, StartIndex, getData.Length - StartIndex);//从新将接受的消息写入内存流
|
||||
reciveMemoryStream.Write(getData, StartIndex, getData.Length - StartIndex);//从新将接受的消息写入内存流
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
//把头去掉,就可以吃了,蛋白质是牛肉的六倍
|
||||
//DataCallBackReady(getData.Skip(StartIndex+4).Take(HeadLength-4).ToArray());
|
||||
|
||||
int CoreLenght = HeadLength - 4;
|
||||
//改为Array.Copy 提升效率
|
||||
//byte[] retData = new byte[CoreLenght];
|
||||
//Array.Copy(getData, StartIndex + 4, retData, 0, CoreLenght);
|
||||
//DataCallBackReady(retData);
|
||||
|
||||
//用Span
|
||||
Span<byte> getData_span = getData;
|
||||
@ -355,7 +295,6 @@ namespace HaoYueNet.ClientNetwork
|
||||
|
||||
public void LogOut(string Msg)
|
||||
{
|
||||
//Console.WriteLine(Msg);
|
||||
OnLogOut(Msg);
|
||||
}
|
||||
|
||||
|
@ -1,4 +1,5 @@
|
||||
using System.Net;
|
||||
using System.Buffers;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using static HaoYueNet.ClientNetwork.BaseData;
|
||||
|
||||
@ -7,7 +8,7 @@ namespace HaoYueNet.ClientNetwork.OtherMode
|
||||
public class NetworkHelperCore_ListenerMode
|
||||
{
|
||||
private Socket serversocket;
|
||||
private Dictionary<nint,Socket> mDictHandleClient;
|
||||
private Dictionary<nint, Socket> mDictHandleClient;
|
||||
|
||||
//响应倒计时计数最大值
|
||||
private static int MaxRevIndexNum = 50;
|
||||
@ -26,12 +27,12 @@ namespace HaoYueNet.ClientNetwork.OtherMode
|
||||
public static int LastConnectPort;
|
||||
public bool bDetailedLog = false;
|
||||
|
||||
public void Init(int port)
|
||||
public void Init(int port, AddressFamily addressFamily = AddressFamily.InterNetwork)
|
||||
{
|
||||
mDictHandleClient = new Dictionary<nint, Socket>();
|
||||
|
||||
LogOut("==>初始化NetworkHelperCore_ListenerMode");
|
||||
serversocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
||||
serversocket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp);
|
||||
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, port);
|
||||
serversocket.Bind(endPoint); // 绑定
|
||||
serversocket.Listen(1);
|
||||
@ -110,7 +111,7 @@ namespace HaoYueNet.ClientNetwork.OtherMode
|
||||
//data = SendDataWithHead(data);
|
||||
try
|
||||
{
|
||||
SendWithIndex(socket,data);
|
||||
SendWithIndex(socket, data);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@ -125,7 +126,7 @@ namespace HaoYueNet.ClientNetwork.OtherMode
|
||||
/// 发送数据并计数
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
private void SendWithIndex(Socket socket,byte[] data)
|
||||
private void SendWithIndex(Socket socket, byte[] data)
|
||||
{
|
||||
//增加发送计数
|
||||
SendIndex = MaxSendIndexNum;
|
||||
@ -182,46 +183,61 @@ namespace HaoYueNet.ClientNetwork.OtherMode
|
||||
OnCloseReady(socket);
|
||||
}
|
||||
|
||||
private void DataCallBackReady(Socket socket,byte[] data)
|
||||
private void DataCallBackReady(Socket socket, byte[] data)
|
||||
{
|
||||
//增加接收计数
|
||||
RevIndex = MaxRevIndexNum;
|
||||
OnReceive(socket,data);
|
||||
OnReceive(socket, data);
|
||||
}
|
||||
|
||||
MemoryStream reciveMemoryStream = new MemoryStream();//开辟一个内存流
|
||||
//byte[] reciveBuffer = new byte[1024 * 1024 * 2];
|
||||
private void Recive(object o)
|
||||
{
|
||||
MemoryStream memoryStream = new MemoryStream();//开辟一个内存流
|
||||
var client = o as Socket;
|
||||
//MemoryStream memoryStream = new MemoryStream();//开辟一个内存流
|
||||
|
||||
while (true)
|
||||
{
|
||||
byte[] buffer = new byte[1024 * 1024 * 2];
|
||||
//申请byte池 一定要记得回收!!
|
||||
byte[] rev_fromArrayPool = ArrayPool<byte>.Shared.Rent(1024 * 1024 * 2);
|
||||
|
||||
int effective = 0;
|
||||
try
|
||||
{
|
||||
effective = client.Receive(buffer);
|
||||
if (effective == 0)
|
||||
effective = client.Receive(rev_fromArrayPool);
|
||||
if (effective == 0)//为0表示已经断开连接,放到后面处理
|
||||
{
|
||||
continue;
|
||||
//清理数据
|
||||
reciveMemoryStream.SetLength(0);
|
||||
reciveMemoryStream.Seek(0, SeekOrigin.Begin);
|
||||
//远程主机强迫关闭了一个现有的连接
|
||||
OnCloseReady(client);
|
||||
//回收
|
||||
ArrayPool<byte>.Shared.Return(rev_fromArrayPool);
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//清理数据
|
||||
reciveMemoryStream.SetLength(0);
|
||||
reciveMemoryStream.Seek(0, SeekOrigin.Begin);
|
||||
|
||||
//远程主机强迫关闭了一个现有的连接
|
||||
OnCloseReady(client);
|
||||
return;
|
||||
//断开连接
|
||||
}
|
||||
if (effective > 0)//如果接受到的消息不为0(不为空)
|
||||
{
|
||||
memoryStream.Write(buffer, 0, effective);//将接受到的数据写入内存流中
|
||||
DataCallBackReady(client, memoryStream.ToArray());
|
||||
|
||||
reciveMemoryStream.Write(rev_fromArrayPool, 0, effective);//将接受到的数据写入内存流中
|
||||
|
||||
//回收
|
||||
ArrayPool<byte>.Shared.Return(rev_fromArrayPool);
|
||||
|
||||
DataCallBackReady(client, reciveMemoryStream.ToArray());
|
||||
//流复用的方式 不用重新new申请
|
||||
memoryStream.Position = 0;
|
||||
memoryStream.SetLength(0);
|
||||
}
|
||||
reciveMemoryStream.Position = 0;
|
||||
reciveMemoryStream.SetLength(0);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -32,7 +32,7 @@ namespace HaoYueNet.ClientNetwork.OtherMode
|
||||
public static int LastConnectPort;
|
||||
public bool bDetailedLog = false;
|
||||
|
||||
public bool Init(string IP, int port, bool isHadDetailedLog = true, bool bBindReuseAddress = false, int bBindport = 0)
|
||||
public bool Init(string IP, int port, bool isHadDetailedLog = true, bool bBindReuseAddress = false, int bBindport = 0, AddressFamily addressFamily = AddressFamily.InterNetwork)
|
||||
{
|
||||
LogOut("==>初始化网络核心");
|
||||
|
||||
@ -40,7 +40,7 @@ namespace HaoYueNet.ClientNetwork.OtherMode
|
||||
RevIndex = MaxRevIndexNum;
|
||||
SendIndex = MaxSendIndexNum;
|
||||
|
||||
client = new Socket(SocketType.Stream, ProtocolType.Tcp);
|
||||
client = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp);
|
||||
if (bBindReuseAddress)
|
||||
{
|
||||
client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
|
||||
@ -192,39 +192,44 @@ namespace HaoYueNet.ClientNetwork.OtherMode
|
||||
OnReceiveData(data);
|
||||
}
|
||||
|
||||
MemoryStream memoryStream = new MemoryStream();//开辟一个内存流
|
||||
MemoryStream reciveMemoryStream = new MemoryStream();//开辟一个反复使用的内存流
|
||||
byte[] reciveBuffer = new byte[1024 * 1024 * 2];//开辟一个反复使用的byte[]
|
||||
private void Recive(object o)
|
||||
{
|
||||
var client = o as Socket;
|
||||
//MemoryStream memoryStream = new MemoryStream();//开辟一个内存流
|
||||
|
||||
while (true)
|
||||
{
|
||||
byte[] buffer = new byte[1024 * 1024 * 2];
|
||||
int effective = 0;
|
||||
try
|
||||
{
|
||||
effective = client.Receive(buffer);
|
||||
if (effective == 0)
|
||||
effective = client.Receive(reciveBuffer);
|
||||
if (effective == 0)//为0表示已经断开连接,放到后面处理
|
||||
{
|
||||
continue;
|
||||
//尝试性,清理数据
|
||||
reciveMemoryStream.SetLength(0);
|
||||
reciveMemoryStream.Seek(0, SeekOrigin.Begin);
|
||||
//远程主机强迫关闭了一个现有的连接
|
||||
OnCloseReady();
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//尝试性,清理数据
|
||||
reciveMemoryStream.SetLength(0);
|
||||
reciveMemoryStream.Seek(0, SeekOrigin.Begin);
|
||||
|
||||
//断开连接
|
||||
//远程主机强迫关闭了一个现有的连接
|
||||
OnCloseReady();
|
||||
return;
|
||||
//断开连接
|
||||
}
|
||||
if (effective > 0)//如果接受到的消息不为0(不为空)
|
||||
{
|
||||
memoryStream.Write(buffer, 0, effective);//将接受到的数据写入内存流中
|
||||
DataCallBackReady(memoryStream.ToArray());
|
||||
|
||||
reciveMemoryStream.Write(reciveBuffer, 0, effective);//将接受到的数据写入内存流中
|
||||
DataCallBackReady(reciveMemoryStream.ToArray());
|
||||
//流复用的方式 不用重新new申请
|
||||
memoryStream.Position = 0;
|
||||
memoryStream.SetLength(0);
|
||||
}
|
||||
reciveMemoryStream.Position = 0;
|
||||
reciveMemoryStream.SetLength(0);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,167 +0,0 @@
|
||||
using System;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace HaoYueNet.ClientNetworkNet4x
|
||||
{
|
||||
public static class BaseData
|
||||
{
|
||||
/// <summary>
|
||||
/// 心跳包数据
|
||||
/// </summary>
|
||||
public static byte[] HeartbeatData = new byte[5] { 0x05, 0x00, 0x00, 0x00, 0x00 };
|
||||
|
||||
public static void writeInt(byte[] buf, int offset, int value)
|
||||
{
|
||||
buf[offset++] = (byte)(255 & value);
|
||||
buf[offset++] = (byte)(255 & value >> 8);
|
||||
buf[offset++] = (byte)(255 & value >> 16);
|
||||
//buf[offset++] = (byte)(255 & value >>> 24);
|
||||
buf[offset++] = (byte)(255 & value >> 24);
|
||||
}
|
||||
|
||||
public static void writeUInt16(byte[] buf, int offset, int value)
|
||||
{
|
||||
buf[offset++] = (byte)(255 & value);
|
||||
buf[offset++] = (byte)(255 & value >> 8);
|
||||
}
|
||||
|
||||
public static class HunterNet_Heartbeat
|
||||
{
|
||||
public static void SetDataToSocketAsyncEventArgs(SocketAsyncEventArgs myreadEventArgs)
|
||||
{
|
||||
myreadEventArgs.SetBuffer(HeartbeatData, 0, HeartbeatData.Length);
|
||||
}
|
||||
}
|
||||
|
||||
public static class HunterNet_S2C
|
||||
{
|
||||
public static void SetDataToSocketAsyncEventArgs(SocketAsyncEventArgs myreadEventArgs, UInt16 CmdID, UInt16 Error, byte[] AddonBytes_Data)
|
||||
{
|
||||
byte[] data = CreatePkgData(CmdID, Error, AddonBytes_Data);
|
||||
myreadEventArgs.SetBuffer(data,0, data.Length);
|
||||
}
|
||||
|
||||
public static byte[] CreatePkgData(UInt16 CmdID, UInt16 Error, byte[] AddonBytes_Data)
|
||||
{
|
||||
//byte[] AddonBytes_CmdID = BitConverter.GetBytes(CmdID);
|
||||
//byte[] AddonBytes_Error = BitConverter.GetBytes(Error);
|
||||
//int AllLenght = AddonBytes_CmdID.Length + AddonBytes_Error.Length + AddonBytes_Data.Length + 4;
|
||||
//int LastIndex = 0;
|
||||
////包长度
|
||||
//byte[] AddonBytes_Lenght = BitConverter.GetBytes(AllLenght);
|
||||
|
||||
//byte[] BufferData = new byte[AllLenght];
|
||||
////包长度
|
||||
//AddonBytes_Lenght.CopyTo(BufferData, LastIndex);
|
||||
//LastIndex += AddonBytes_Lenght.Length;
|
||||
|
||||
////CMDID
|
||||
//AddonBytes_CmdID.CopyTo(BufferData, LastIndex);
|
||||
//LastIndex += AddonBytes_CmdID.Length;
|
||||
|
||||
////Error
|
||||
//AddonBytes_Error.CopyTo(BufferData, LastIndex);
|
||||
//LastIndex += AddonBytes_Error.Length;
|
||||
|
||||
////DATA
|
||||
//AddonBytes_Data.CopyTo(BufferData, LastIndex);
|
||||
//LastIndex += AddonBytes_Data.Length;
|
||||
//return BufferData;
|
||||
|
||||
////用Buffer.BlockCopy拷贝
|
||||
//byte[] AddonBytes_CmdID = BitConverter.GetBytes(CmdID);
|
||||
//byte[] AddonBytes_Error = BitConverter.GetBytes(Error);
|
||||
//int AllLenght = AddonBytes_CmdID.Length + AddonBytes_Error.Length + AddonBytes_Data.Length + 4;
|
||||
//int LastIndex = 0;
|
||||
////包长度
|
||||
//byte[] AddonBytes_Lenght = BitConverter.GetBytes(AllLenght);
|
||||
|
||||
//byte[] BufferData = new byte[AllLenght];
|
||||
////包长度
|
||||
//Buffer.BlockCopy(AddonBytes_Lenght, 0, BufferData, LastIndex, AddonBytes_Lenght.Length);
|
||||
//LastIndex += AddonBytes_Lenght.Length;
|
||||
|
||||
////CMDID
|
||||
//Buffer.BlockCopy(AddonBytes_CmdID, 0, BufferData, LastIndex, AddonBytes_CmdID.Length);
|
||||
//LastIndex += AddonBytes_CmdID.Length;
|
||||
|
||||
////Error
|
||||
//Buffer.BlockCopy(AddonBytes_Error, 0, BufferData, LastIndex, AddonBytes_Error.Length);
|
||||
//LastIndex += AddonBytes_Error.Length;
|
||||
|
||||
////DATA
|
||||
//Buffer.BlockCopy(AddonBytes_Data, 0, BufferData, LastIndex, AddonBytes_Data.Length);
|
||||
//LastIndex += AddonBytes_Data.Length;
|
||||
|
||||
|
||||
|
||||
//用Buffer.BlockCopy拷贝
|
||||
//包长度
|
||||
int AllLenght = 4 + 2 + 2 + AddonBytes_Data.Length;
|
||||
byte[] BufferData = new byte[AllLenght];
|
||||
|
||||
//包长度
|
||||
writeInt(BufferData, 0, AllLenght);
|
||||
|
||||
//CMDID
|
||||
writeUInt16(BufferData, 4, CmdID);
|
||||
|
||||
//Error
|
||||
writeUInt16(BufferData, 4 + 2, CmdID);
|
||||
|
||||
//DATA
|
||||
Buffer.BlockCopy(AddonBytes_Data, 0, BufferData, 4 + 2 + 2, AddonBytes_Data.Length);
|
||||
|
||||
return BufferData;
|
||||
}
|
||||
|
||||
public static void AnalysisPkgData(byte[] srcdata, out UInt16 CmdID, out UInt16 Error, out byte[] data)
|
||||
{
|
||||
CmdID = BitConverter.ToUInt16(srcdata, 0);
|
||||
Error = BitConverter.ToUInt16(srcdata, 2);
|
||||
data = new byte[srcdata.Length - 2 - 2];
|
||||
Array.Copy(srcdata, 4, data, 0, data.Length);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public static class HunterNet_C2S
|
||||
{
|
||||
public static void SetDataToSocketAsyncEventArgs(SocketAsyncEventArgs myreadEventArgs, UInt16 CmdID, byte[] AddonBytes_Data)
|
||||
{
|
||||
byte[] data = CreatePkgData(CmdID, AddonBytes_Data);
|
||||
myreadEventArgs.SetBuffer(data, 0, data.Length);
|
||||
}
|
||||
|
||||
public static byte[] CreatePkgData(UInt16 CmdID, byte[] AddonBytes_Data)
|
||||
{
|
||||
byte[] AddonBytes_CmdID = BitConverter.GetBytes(CmdID);
|
||||
int AllLenght = AddonBytes_CmdID.Length + AddonBytes_Data.Length + 4;
|
||||
int LastIndex = 0;
|
||||
//包长度
|
||||
byte[] AddonBytes_Lenght = BitConverter.GetBytes(AllLenght);
|
||||
|
||||
byte[] BufferData = new byte[AllLenght];
|
||||
//包长度
|
||||
Buffer.BlockCopy(AddonBytes_Lenght, 0, BufferData, LastIndex, AddonBytes_Lenght.Length);
|
||||
LastIndex += AddonBytes_Lenght.Length;
|
||||
|
||||
//CMDID
|
||||
Buffer.BlockCopy(AddonBytes_CmdID, 0, BufferData, LastIndex, AddonBytes_CmdID.Length);
|
||||
LastIndex += AddonBytes_CmdID.Length;
|
||||
|
||||
//DATA
|
||||
Buffer.BlockCopy(AddonBytes_Data, 0, BufferData, LastIndex, AddonBytes_Data.Length);
|
||||
LastIndex += AddonBytes_Data.Length;
|
||||
return BufferData;
|
||||
}
|
||||
|
||||
public static void AnalysisPkgData(byte[] srcdata, out UInt16 CmdID, out byte[] data)
|
||||
{
|
||||
data = new byte[srcdata.Length - 2];
|
||||
CmdID = BitConverter.ToUInt16(srcdata, 0);
|
||||
Array.Copy(srcdata, 2, data, 0, data.Length);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -1,67 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProjectGuid>{A741610F-29B9-4F0E-9A3D-0B3E1318F031}</ProjectGuid>
|
||||
<OutputType>Library</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>HaoYueNet.ClientNetworkNet4x</RootNamespace>
|
||||
<AssemblyName>HaoYueNet.ClientNetworkNet4x</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<Deterministic>true</Deterministic>
|
||||
<TargetFrameworkProfile />
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>bin\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
<Prefer32Bit>false</Prefer32Bit>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<!--避免 错误 CS8630 无效的 nullable 值: C# 7.3 的“Enable”。请使用语言版本 8.0 或更高版本 -->
|
||||
<LangVersion>8.0</LangVersion>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
<Prefer32Bit>false</Prefer32Bit>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="Microsoft.CSharp" />
|
||||
<Reference Include="System.Buffers, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
|
||||
<HintPath>..\..\packages\System.Buffers.4.5.1\lib\netstandard1.1\System.Buffers.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.Data" />
|
||||
<Reference Include="System.Memory, Version=4.0.1.2, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
|
||||
<HintPath>..\..\packages\System.Memory.4.5.5\lib\netstandard1.1\System.Memory.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.Runtime.CompilerServices.Unsafe, Version=4.0.4.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
|
||||
<HintPath>..\..\packages\System.Runtime.CompilerServices.Unsafe.4.5.3\lib\netstandard1.0\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="BaseData.cs" />
|
||||
<Compile Include="NetworkHelperCore.cs" />
|
||||
<Compile Include="NetworkHelperP2PCore.cs" />
|
||||
<Compile Include="OtherMode\NetworkHelperCore_ListenerMode.cs" />
|
||||
<Compile Include="OtherMode\NetworkHelperCore_SourceMode.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="app.config" />
|
||||
<None Include="packages.config" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
</Project>
|
@ -1,385 +0,0 @@
|
||||
//using HunterProtobufCore;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
using static HaoYueNet.ClientNetworkNet4x.BaseData;
|
||||
|
||||
namespace HaoYueNet.ClientNetworkNet4x
|
||||
{
|
||||
public class NetworkHelperCore
|
||||
{
|
||||
private Socket client;
|
||||
|
||||
|
||||
////响应倒计时计数最大值
|
||||
//private static int MaxRevIndexNum = 6;
|
||||
|
||||
////发送倒计时计数最大值
|
||||
//private static int MaxSendIndexNum = 3;
|
||||
|
||||
//响应倒计时计数最大值
|
||||
private static int MaxRevIndexNum = 50;
|
||||
|
||||
//发送倒计时计数最大值
|
||||
private static int MaxSendIndexNum = 3;
|
||||
|
||||
//响应倒计时计数
|
||||
private static int RevIndex=0;
|
||||
//发送倒计时计数
|
||||
private static int SendIndex=0;
|
||||
|
||||
//计时器间隔
|
||||
private static int TimerInterval = 3000;
|
||||
|
||||
private System.Timers.Timer _heartTimer;
|
||||
|
||||
public static string LastConnectIP;
|
||||
public static int LastConnectPort;
|
||||
public bool bDetailedLog = false;
|
||||
|
||||
public bool Init(string IP, int port,bool isHadDetailedLog = true, bool bBindReuseAddress = false,int bBindport = 0)
|
||||
{
|
||||
LogOut("==>初始化网络核心");
|
||||
|
||||
bDetailedLog = isHadDetailedLog;
|
||||
RevIndex = MaxRevIndexNum;
|
||||
SendIndex = MaxSendIndexNum;
|
||||
|
||||
client = new Socket(SocketType.Stream, ProtocolType.Tcp);
|
||||
if (bBindReuseAddress)
|
||||
{
|
||||
client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
|
||||
IPEndPoint ipe = new IPEndPoint(IPAddress.Any, Convert.ToInt32(bBindport));
|
||||
client.Bind(ipe);
|
||||
}
|
||||
LastConnectIP = IP;
|
||||
LastConnectPort = port;
|
||||
return Connect(IP, port);
|
||||
}
|
||||
|
||||
bool Connect(string IP, int port)
|
||||
{
|
||||
//带回调的
|
||||
try
|
||||
{
|
||||
if(bDetailedLog)
|
||||
LogOut("连接到远程IP " + IP + ":" + port);
|
||||
else
|
||||
LogOut("连接到远程服务");
|
||||
|
||||
client.Connect(IP, port);
|
||||
Thread thread = new Thread(Recive);
|
||||
thread.IsBackground = true;
|
||||
thread.Start(client);
|
||||
int localport = ((IPEndPoint)client.LocalEndPoint).Port;
|
||||
|
||||
if (bDetailedLog)
|
||||
LogOut($"连接成功!连接到远程IP->{IP}:{port} | 本地端口->{localport}");
|
||||
else
|
||||
LogOut("连接成功!");
|
||||
|
||||
if (_heartTimer == null)
|
||||
{
|
||||
_heartTimer = new System.Timers.Timer();
|
||||
}
|
||||
_heartTimer.Interval = TimerInterval;
|
||||
_heartTimer.Elapsed += CheckUpdatetimer_Elapsed;
|
||||
_heartTimer.AutoReset = true;
|
||||
_heartTimer.Enabled = true;
|
||||
|
||||
if (bDetailedLog)
|
||||
LogOut("开启心跳包检测");
|
||||
|
||||
OnConnected?.Invoke(true);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (bDetailedLog)
|
||||
LogOut("连接失败:" + ex.ToString());
|
||||
else
|
||||
LogOut("连接失败");
|
||||
|
||||
OnConnected?.Invoke(false);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
~NetworkHelperCore()
|
||||
{
|
||||
client.Close();
|
||||
}
|
||||
|
||||
private void SendToSocket(byte[] data)
|
||||
{
|
||||
//已拼接包长度,这里不再需要拼接长度
|
||||
//data = SendDataWithHead(data);
|
||||
try
|
||||
{
|
||||
SendWithIndex(data);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//连接断开
|
||||
OnCloseReady();
|
||||
return;
|
||||
}
|
||||
//LogOut("发送消息,消息长度=> "+data.Length);
|
||||
}
|
||||
|
||||
private void SendHeartbeat()
|
||||
{
|
||||
try
|
||||
{
|
||||
SendWithIndex(HeartbeatData);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//连接断开
|
||||
OnCloseReady();
|
||||
return;
|
||||
}
|
||||
//LogOut("发送心跳包");
|
||||
}
|
||||
|
||||
object sendLock = new object();
|
||||
/// <summary>
|
||||
/// 发送数据并计数
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
private void SendWithIndex(byte[] data)
|
||||
{
|
||||
lock (sendLock)
|
||||
{
|
||||
//增加发送计数
|
||||
SendIndex = MaxSendIndexNum;
|
||||
//发送数据
|
||||
client.Send(data);
|
||||
}
|
||||
}
|
||||
|
||||
////拼接头长度
|
||||
//private byte[] SendDataWithHead(byte[] message)
|
||||
//{
|
||||
|
||||
// MemoryStream memoryStream = new MemoryStream();//创建一个内存流
|
||||
|
||||
// byte[] BagHead = BitConverter.GetBytes(message.Length + 4);//往字节数组中写入包头(包头自身的长度和消息体的长度)的长度
|
||||
|
||||
// memoryStream.Write(BagHead, 0, BagHead.Length);//将包头写入内存流
|
||||
|
||||
// memoryStream.Write(message, 0, message.Length);//将消息体写入内存流
|
||||
|
||||
// byte[] HeadAndBody = memoryStream.ToArray();//将内存流中的数据写入字节数组
|
||||
|
||||
// memoryStream.Close();//关闭内存
|
||||
// memoryStream.Dispose();//释放资源
|
||||
|
||||
// return HeadAndBody;
|
||||
//}
|
||||
|
||||
/// <summary>
|
||||
/// 供外部调用 发送消息
|
||||
/// </summary>
|
||||
/// <param name="CMDID"></param>
|
||||
/// <param name="data">序列化之后的数据</param>
|
||||
public void SendToServer(int CMDID,byte[] data)
|
||||
{
|
||||
//LogOut("准备数据 CMDID=> "+CMDID);
|
||||
/*
|
||||
HunterNet_C2S _c2sdata = new HunterNet_C2S();
|
||||
_c2sdata.HunterNetCoreCmdID = CMDID;
|
||||
_c2sdata.HunterNetCoreData = ByteString.CopyFrom(data);
|
||||
byte[] _finaldata = Serizlize(_c2sdata);
|
||||
*/
|
||||
byte[] _finaldata = HunterNet_C2S.CreatePkgData((ushort)CMDID, data);
|
||||
SendToSocket(_finaldata);
|
||||
}
|
||||
|
||||
#region 事件定义
|
||||
public delegate void OnReceiveDataHandler(int CMDID, int ERRCODE, byte[] data);
|
||||
public delegate void OnConnectedHandler(bool IsConnected);
|
||||
public delegate void OnCloseHandler();
|
||||
public delegate void OnLogOutHandler(string Msg);
|
||||
#endregion
|
||||
|
||||
public event OnConnectedHandler OnConnected;
|
||||
public event OnReceiveDataHandler OnReceiveData;
|
||||
public event OnCloseHandler OnClose;
|
||||
/// <summary>
|
||||
/// 网络库调试日志输出
|
||||
/// </summary>
|
||||
public event OnLogOutHandler OnLogOut;
|
||||
|
||||
/// <summary>
|
||||
/// 做好处理的连接管理
|
||||
/// </summary>
|
||||
private void OnCloseReady()
|
||||
{
|
||||
|
||||
if (bDetailedLog)
|
||||
LogOut("关闭心跳包计数");
|
||||
_heartTimer.Enabled = false;
|
||||
_heartTimer.Elapsed -= CheckUpdatetimer_Elapsed;
|
||||
LogOut("关闭连接");
|
||||
//关闭Socket连接
|
||||
client.Close();
|
||||
OnClose?.Invoke();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 主动关闭连接
|
||||
/// </summary>
|
||||
public void CloseConntect()
|
||||
{
|
||||
OnCloseReady();
|
||||
}
|
||||
|
||||
private void DataCallBackReady(byte[] data)
|
||||
{
|
||||
|
||||
//增加接收计数
|
||||
RevIndex = MaxRevIndexNum;
|
||||
|
||||
//不处理心跳包
|
||||
if (data.Length == 1 && data[0] == 0x00)
|
||||
{
|
||||
//LogOut("收到心跳包");
|
||||
return;
|
||||
}
|
||||
|
||||
/*
|
||||
HunterNet_S2C _c2s = DeSerizlize<HunterNet_S2C>(data);
|
||||
|
||||
OnReceiveData(_c2s.HunterNetCoreCmdID, _c2s.HunterNetCoreERRORCode, _c2s.HunterNetCoreData.ToArray());
|
||||
*/
|
||||
|
||||
HunterNet_S2C.AnalysisPkgData(data, out ushort CmdID, out ushort Error, out byte[] resultdata);
|
||||
OnReceiveData(CmdID, Error, resultdata);
|
||||
}
|
||||
|
||||
|
||||
MemoryStream memoryStream = new MemoryStream();//开辟一个内存流
|
||||
private void Recive(object o)
|
||||
{
|
||||
var client = o as Socket;
|
||||
//MemoryStream memoryStream = new MemoryStream();//开辟一个内存流
|
||||
|
||||
while (true)
|
||||
{
|
||||
byte[] buffer = new byte[1024 * 1024 * 2];
|
||||
int effective=0;
|
||||
try
|
||||
{
|
||||
effective = client.Receive(buffer);
|
||||
if (effective == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
catch(Exception ex)
|
||||
{
|
||||
//远程主机强迫关闭了一个现有的连接
|
||||
OnCloseReady();
|
||||
return;
|
||||
//断开连接
|
||||
}
|
||||
|
||||
|
||||
memoryStream.Write(buffer, 0, effective);//将接受到的数据写入内存流中
|
||||
byte[] getData = memoryStream.ToArray();//将内存流中的消息体写入字节数组
|
||||
int StartIndex = 0;//设置一个读取数据的起始下标
|
||||
|
||||
while (true)
|
||||
{
|
||||
if (effective > 0)//如果接受到的消息不为0(不为空)
|
||||
{
|
||||
int HeadLength = 0;//包头长度(包头+包体)
|
||||
if (getData.Length - StartIndex < 4)//包头接受不完整
|
||||
{
|
||||
HeadLength = -1;
|
||||
}
|
||||
else
|
||||
{
|
||||
//如果包头接受完整 转换成int类型的数值
|
||||
HeadLength = BitConverter.ToInt32(getData, StartIndex);
|
||||
}
|
||||
//包头接受完整但是消息体不完整 //包头接受不完整
|
||||
//↓↓↓↓↓↓↓↓ ↓↓↓
|
||||
if (getData.Length - StartIndex < HeadLength || HeadLength == -1)
|
||||
{
|
||||
/* 一种清空流的方式
|
||||
memoryStream.Close();//关闭内存流
|
||||
memoryStream.Dispose();//释放内存资源
|
||||
memoryStream = new MemoryStream();//创建新的内存流
|
||||
*/
|
||||
|
||||
//流复用的方式 不用重新new申请
|
||||
memoryStream.Position = 0;
|
||||
memoryStream.SetLength(0);
|
||||
|
||||
memoryStream.Write(getData, StartIndex, getData.Length - StartIndex);//从新将接受的消息写入内存流
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
//把头去掉,就可以吃了,蛋白质是牛肉的六倍
|
||||
//DataCallBackReady(getData.Skip(StartIndex+4).Take(HeadLength-4).ToArray());
|
||||
|
||||
int CoreLenght = HeadLength - 4;
|
||||
|
||||
//改为Array.Copy 提升效率
|
||||
//byte[] retData = new byte[CoreLenght];
|
||||
//Array.Copy(getData, StartIndex + 4, retData, 0, CoreLenght);
|
||||
//DataCallBackReady(retData);
|
||||
|
||||
//用Span
|
||||
Span<byte> getData_span = getData;
|
||||
getData_span = getData_span.Slice(StartIndex + 4,CoreLenght);
|
||||
DataCallBackReady(getData_span.ToArray());
|
||||
|
||||
StartIndex += HeadLength;//当读取一条完整的数据后,读取数据的起始下标应为当前接受到的消息体的长度(当前数据的尾部或下一条消息的首部)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private void CheckUpdatetimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
|
||||
{
|
||||
//接收服务器数据计数
|
||||
RevIndex--;
|
||||
if (RevIndex <= 0)
|
||||
{
|
||||
//判定掉线
|
||||
OnCloseReady();
|
||||
return;
|
||||
}
|
||||
|
||||
//发送计数
|
||||
SendIndex--;
|
||||
if (SendIndex <= 0)//需要发送心跳包了
|
||||
{
|
||||
//重置倒计时计数
|
||||
SendIndex = MaxSendIndexNum;
|
||||
|
||||
SendHeartbeat();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void LogOut(string Msg)
|
||||
{
|
||||
//Console.WriteLine(Msg);
|
||||
OnLogOut?.Invoke(Msg);
|
||||
}
|
||||
|
||||
public Socket GetClientSocket()
|
||||
{
|
||||
return client;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,371 +0,0 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
using static HaoYueNet.ClientNetworkNet4x.BaseData;
|
||||
|
||||
namespace HaoYueNet.ClientNetworkNet4x
|
||||
{
|
||||
public class NetworkHelperP2PCore
|
||||
{
|
||||
private Socket client;
|
||||
|
||||
//响应倒计时计数最大值
|
||||
private static int MaxRevIndexNum = 50;
|
||||
|
||||
//发送倒计时计数最大值
|
||||
private static int MaxSendIndexNum = 3;
|
||||
|
||||
//响应倒计时计数
|
||||
private static int RevIndex=0;
|
||||
//发送倒计时计数
|
||||
private static int SendIndex=0;
|
||||
|
||||
//计时器间隔
|
||||
private static int TimerInterval = 3000;
|
||||
|
||||
private System.Timers.Timer _heartTimer;
|
||||
|
||||
public void Init(string IP, int port, bool bBindReuseAddress = false,int bBindport = 0)
|
||||
{
|
||||
|
||||
LogOut("==>初始化网络核心");
|
||||
|
||||
RevIndex = MaxRevIndexNum;
|
||||
SendIndex = MaxSendIndexNum;
|
||||
|
||||
client = new Socket(SocketType.Stream, ProtocolType.Tcp);
|
||||
if (bBindReuseAddress)
|
||||
{
|
||||
client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
|
||||
IPEndPoint ipe = new IPEndPoint(IPAddress.Any, Convert.ToInt32(bBindport));
|
||||
client.Bind(ipe);
|
||||
}
|
||||
Connect(IP, port);
|
||||
}
|
||||
|
||||
public bool Connect(string IP, int port)
|
||||
{
|
||||
//带回调的
|
||||
try
|
||||
{
|
||||
LogOut("连接到远程IP " + IP + ":" + port);
|
||||
client.Connect(IP, port);
|
||||
Thread thread = new Thread(Recive);
|
||||
thread.IsBackground = true;
|
||||
thread.Start(client);
|
||||
int localport = ((IPEndPoint)client.LocalEndPoint).Port;
|
||||
LogOut($"连接成功!连接到远程IP->{IP}:{port} | 本地端口->{localport}");
|
||||
|
||||
if (_heartTimer == null)
|
||||
{
|
||||
_heartTimer = new System.Timers.Timer();
|
||||
}
|
||||
_heartTimer.Interval = TimerInterval;
|
||||
_heartTimer.Elapsed += CheckUpdatetimer_Elapsed;
|
||||
_heartTimer.AutoReset = true;
|
||||
_heartTimer.Enabled = true;
|
||||
LogOut("开启心跳包检测");
|
||||
|
||||
OnConnected(true);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogOut("连接失败:" + ex.ToString());
|
||||
OnConnected(false);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
~NetworkHelperP2PCore()
|
||||
{
|
||||
client.Close();
|
||||
}
|
||||
|
||||
private void SendToSocket(byte[] data)
|
||||
{
|
||||
//已拼接包长度,这里不再需要拼接长度
|
||||
//data = SendDataWithHead(data);
|
||||
try
|
||||
{
|
||||
SendWithIndex(data);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//连接断开
|
||||
OnCloseReady();
|
||||
return;
|
||||
}
|
||||
//LogOut("发送消息,消息长度=> "+data.Length);
|
||||
}
|
||||
|
||||
private void SendHeartbeat()
|
||||
{
|
||||
try
|
||||
{
|
||||
SendWithIndex(BaseData.HeartbeatData);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//连接断开
|
||||
OnCloseReady();
|
||||
return;
|
||||
}
|
||||
//LogOut("发送心跳包");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发送数据并计数
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
private void SendWithIndex(byte[] data)
|
||||
{
|
||||
//增加发送计数
|
||||
SendIndex = MaxSendIndexNum;
|
||||
//发送数据
|
||||
client.Send(data);
|
||||
}
|
||||
|
||||
////拼接头长度
|
||||
//private byte[] SendDataWithHead(byte[] message)
|
||||
//{
|
||||
|
||||
// MemoryStream memoryStream = new MemoryStream();//创建一个内存流
|
||||
|
||||
// byte[] BagHead = BitConverter.GetBytes(message.Length + 4);//往字节数组中写入包头(包头自身的长度和消息体的长度)的长度
|
||||
|
||||
// memoryStream.Write(BagHead, 0, BagHead.Length);//将包头写入内存流
|
||||
|
||||
// memoryStream.Write(message, 0, message.Length);//将消息体写入内存流
|
||||
|
||||
// byte[] HeadAndBody = memoryStream.ToArray();//将内存流中的数据写入字节数组
|
||||
|
||||
// memoryStream.Close();//关闭内存
|
||||
// memoryStream.Dispose();//释放资源
|
||||
|
||||
// return HeadAndBody;
|
||||
//}
|
||||
|
||||
/// <summary>
|
||||
/// 供外部调用 发送消息
|
||||
/// </summary>
|
||||
/// <param name="CMDID"></param>
|
||||
/// <param name="ERRCODE"></param>
|
||||
/// <param name="data"></param>
|
||||
public void SendToSocket(int CMDID, int ERRCODE, byte[] data)
|
||||
{
|
||||
//LogOut("准备数据 CMDID=> "+CMDID);
|
||||
/*HunterNet_S2C _s2sdata = new HunterNet_S2C();
|
||||
_s2sdata.HunterNetCoreCmdID = CMDID;
|
||||
_s2sdata.HunterNetCoreERRORCode = ERRCODE;
|
||||
_s2sdata.HunterNetCoreData = ByteString.CopyFrom(data);
|
||||
byte[] _finaldata = Serizlize(_s2sdata);*/
|
||||
|
||||
byte[] _finaldata = HunterNet_S2C.CreatePkgData((ushort)CMDID, (ushort)ERRCODE, data);
|
||||
SendToSocket(_finaldata);
|
||||
}
|
||||
|
||||
public delegate void OnDataCallBack_Data(int CMDID, int ERRCODE, byte[] data);
|
||||
|
||||
public event OnDataCallBack_Data OnDataCallBack;
|
||||
|
||||
public delegate void delegate_NoData();
|
||||
|
||||
public delegate void delegate_Bool(bool IsConnected);
|
||||
|
||||
public event delegate_NoData OnClose;
|
||||
|
||||
public event delegate_Bool OnConnected;
|
||||
|
||||
public delegate void delegate_str(string Msg);
|
||||
|
||||
/// <summary>
|
||||
/// 网络库调试日志输出
|
||||
/// </summary>
|
||||
public event delegate_str OnLogOut;
|
||||
|
||||
///// <summary>
|
||||
///// 用于调用者回调的虚函数
|
||||
///// </summary>
|
||||
///// <param name="data"></param>
|
||||
//public virtual void DataCallBack(int CMDID,int ERRCODE,byte[] data)
|
||||
//{
|
||||
|
||||
//}
|
||||
|
||||
///// <summary>
|
||||
///// 断开连接
|
||||
///// </summary>
|
||||
///// <param name="sk"></param>
|
||||
//public virtual void OnClose()
|
||||
//{
|
||||
|
||||
//}
|
||||
|
||||
/// <summary>
|
||||
/// 做好处理的连接管理
|
||||
/// </summary>
|
||||
private void OnCloseReady()
|
||||
{
|
||||
LogOut("关闭心跳包计数");
|
||||
_heartTimer.Enabled = false;
|
||||
_heartTimer.Elapsed -= CheckUpdatetimer_Elapsed;
|
||||
LogOut("关闭连接");
|
||||
//关闭Socket连接
|
||||
client.Close();
|
||||
OnClose();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 主动关闭连接
|
||||
/// </summary>
|
||||
public void CloseConntect()
|
||||
{
|
||||
OnCloseReady();
|
||||
}
|
||||
|
||||
private void DataCallBackReady(byte[] data)
|
||||
{
|
||||
|
||||
//增加接收计数
|
||||
RevIndex = MaxRevIndexNum;
|
||||
|
||||
//不处理心跳包
|
||||
if (data.Length == 1 && data[0] == 0x00)
|
||||
{
|
||||
//LogOut("收到心跳包");
|
||||
return;
|
||||
}
|
||||
|
||||
/*
|
||||
HunterNet_S2C _c2s = DeSerizlize<HunterNet_S2C>(data);
|
||||
OnDataCallBack(_c2s.HunterNetCoreCmdID, _c2s.HunterNetCoreERRORCode, _c2s.HunterNetCoreData.ToArray());
|
||||
*/
|
||||
HunterNet_S2C.AnalysisPkgData(data, out ushort CmdID, out ushort Error, out byte[] resultdata);
|
||||
OnDataCallBack(CmdID, Error, resultdata);
|
||||
}
|
||||
|
||||
MemoryStream memoryStream = new MemoryStream();//开辟一个内存流
|
||||
private void Recive(object o)
|
||||
{
|
||||
var client = o as Socket;
|
||||
//MemoryStream memoryStream = new MemoryStream();//开辟一个内存流
|
||||
|
||||
while (true)
|
||||
{
|
||||
byte[] buffer = new byte[1024 * 1024 * 2];
|
||||
int effective=0;
|
||||
try
|
||||
{
|
||||
effective = client.Receive(buffer);
|
||||
if (effective == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
catch(Exception ex)
|
||||
{
|
||||
//远程主机强迫关闭了一个现有的连接
|
||||
OnCloseReady();
|
||||
return;
|
||||
//断开连接
|
||||
}
|
||||
|
||||
|
||||
memoryStream.Write(buffer, 0, effective);//将接受到的数据写入内存流中
|
||||
byte[] getData = memoryStream.ToArray();//将内存流中的消息体写入字节数组
|
||||
int StartIndex = 0;//设置一个读取数据的起始下标
|
||||
|
||||
while (true)
|
||||
{
|
||||
|
||||
|
||||
if (effective > 0)//如果接受到的消息不为0(不为空)
|
||||
{
|
||||
int HeadLength = 0;//包头长度(包头+包体)
|
||||
if (getData.Length - StartIndex < 4)//包头接受不完整
|
||||
{
|
||||
HeadLength = -1;
|
||||
}
|
||||
else
|
||||
{
|
||||
//如果包头接受完整 转换成int类型的数值
|
||||
HeadLength = BitConverter.ToInt32(getData, StartIndex);
|
||||
}
|
||||
//包头接受完整但是消息体不完整 //包头接受不完整
|
||||
//↓↓↓↓↓↓↓↓ ↓↓↓
|
||||
if (getData.Length - StartIndex < HeadLength || HeadLength == -1)
|
||||
{
|
||||
/* 一种清空流的方式
|
||||
memoryStream.Close();//关闭内存流
|
||||
memoryStream.Dispose();//释放内存资源
|
||||
memoryStream = new MemoryStream();//创建新的内存流
|
||||
*/
|
||||
|
||||
//流复用的方式 不用重新new申请
|
||||
memoryStream.Position = 0;
|
||||
memoryStream.SetLength(0);
|
||||
|
||||
memoryStream.Write(getData, StartIndex, getData.Length - StartIndex);//从新将接受的消息写入内存流
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
//把头去掉,就可以吃了,蛋白质是牛肉的六倍
|
||||
//DataCallBackReady(getData.Skip(StartIndex+4).Take(HeadLength-4).ToArray());
|
||||
|
||||
int CoreLenght = HeadLength - 4;
|
||||
//改为Array.Copy 提升效率
|
||||
//byte[] retData = new byte[CoreLenght];
|
||||
//Array.Copy(getData, StartIndex + 4, retData, 0, CoreLenght);
|
||||
//DataCallBackReady(retData);
|
||||
|
||||
//用Span
|
||||
Span<byte> getData_span = getData;
|
||||
getData_span = getData_span.Slice(StartIndex + 4, CoreLenght);
|
||||
DataCallBackReady(getData_span.ToArray());
|
||||
|
||||
StartIndex += HeadLength;//当读取一条完整的数据后,读取数据的起始下标应为当前接受到的消息体的长度(当前数据的尾部或下一条消息的首部)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void CheckUpdatetimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
|
||||
{
|
||||
//接收服务器数据计数
|
||||
RevIndex--;
|
||||
if (RevIndex <= 0)
|
||||
{
|
||||
//判定掉线
|
||||
OnCloseReady();
|
||||
return;
|
||||
}
|
||||
|
||||
//发送计数
|
||||
SendIndex--;
|
||||
if (SendIndex <= 0)//需要发送心跳包了
|
||||
{
|
||||
//重置倒计时计数
|
||||
SendIndex = MaxSendIndexNum;
|
||||
|
||||
SendHeartbeat();
|
||||
}
|
||||
}
|
||||
|
||||
public void LogOut(string Msg)
|
||||
{
|
||||
//Console.WriteLine(Msg);
|
||||
OnLogOut(Msg);
|
||||
}
|
||||
|
||||
public Socket GetClientSocket()
|
||||
{
|
||||
return client;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,240 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace HaoYueNet.ClientNetworkNet4x.OtherMode
|
||||
{
|
||||
public class NetworkHelperCore_ListenerMode
|
||||
{
|
||||
private Socket serversocket;
|
||||
private Dictionary<IntPtr, Socket> mDictHandleClient;
|
||||
|
||||
//响应倒计时计数最大值
|
||||
private static int MaxRevIndexNum = 50;
|
||||
|
||||
//发送倒计时计数最大值
|
||||
private static int MaxSendIndexNum = 3;
|
||||
|
||||
//响应倒计时计数
|
||||
private static int RevIndex = 0;
|
||||
//发送倒计时计数
|
||||
private static int SendIndex = 0;
|
||||
//计时器间隔
|
||||
private static int TimerInterval = 3000;
|
||||
|
||||
public static string LastConnectIP;
|
||||
public static int LastConnectPort;
|
||||
public bool bDetailedLog = false;
|
||||
|
||||
public void Init(int port)
|
||||
{
|
||||
mDictHandleClient = new Dictionary<IntPtr, Socket>();
|
||||
|
||||
LogOut("==>初始化NetworkHelperCore_ListenerMode");
|
||||
serversocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
||||
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, port);
|
||||
serversocket.Bind(endPoint); // 绑定
|
||||
serversocket.Listen(1);
|
||||
//client = serversocket.Accept(); // 接收客户端连接
|
||||
//OnConnected?.Invoke(true);
|
||||
//Console.WriteLine("客户端连接成功 信息: " + client.AddressFamily.ToString());
|
||||
//Thread revThread = new Thread(Recive);
|
||||
//revThread.Start(client);
|
||||
|
||||
Task task = new Task(() =>
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
Socket newclient;
|
||||
try
|
||||
{
|
||||
newclient = serversocket.Accept(); // 接收客户端连接
|
||||
}
|
||||
catch
|
||||
{
|
||||
break;
|
||||
}
|
||||
AddDictSocket(newclient);
|
||||
OnConnected?.Invoke(newclient);
|
||||
Console.WriteLine("客户端连接成功 信息: " + newclient.AddressFamily.ToString());
|
||||
Thread revThread = new Thread(Recive);
|
||||
revThread.Start(newclient);
|
||||
}
|
||||
});
|
||||
task.Start();
|
||||
}
|
||||
|
||||
#region
|
||||
|
||||
/// <summary>
|
||||
/// 追加Socket返回下标
|
||||
/// </summary>
|
||||
/// <param name="socket"></param>
|
||||
/// <returns></returns>
|
||||
public void AddDictSocket(Socket socket)
|
||||
{
|
||||
if (socket == null)
|
||||
return;
|
||||
lock (mDictHandleClient)
|
||||
{
|
||||
mDictHandleClient[socket.Handle] = socket;
|
||||
}
|
||||
}
|
||||
|
||||
public void RemoveDictSocket(Socket socket)
|
||||
{
|
||||
if (socket == null)
|
||||
return;
|
||||
lock (mDictHandleClient)
|
||||
{
|
||||
if (!mDictHandleClient.ContainsKey(socket.Handle))
|
||||
return;
|
||||
mDictHandleClient.Remove(socket.Handle);
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
~NetworkHelperCore_ListenerMode()
|
||||
{
|
||||
IntPtr[] keys = mDictHandleClient.Keys.ToArray();
|
||||
for (uint i = 0; i < keys.Length; i++)
|
||||
{
|
||||
mDictHandleClient[keys[i]].Close();
|
||||
}
|
||||
mDictHandleClient.Clear();
|
||||
}
|
||||
|
||||
private void SendToSocket(Socket socket, byte[] data)
|
||||
{
|
||||
//已拼接包长度,这里不再需要拼接长度
|
||||
//data = SendDataWithHead(data);
|
||||
try
|
||||
{
|
||||
SendWithIndex(socket,data);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//连接断开
|
||||
OnCloseReady(socket);
|
||||
return;
|
||||
}
|
||||
//LogOut("发送消息,消息长度=> "+data.Length);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发送数据并计数
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
private void SendWithIndex(Socket socket,byte[] data)
|
||||
{
|
||||
//增加发送计数
|
||||
SendIndex = MaxSendIndexNum;
|
||||
//发送数据
|
||||
socket.Send(data);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 供外部调用 发送消息
|
||||
/// </summary>
|
||||
/// <param name="CMDID"></param>
|
||||
/// <param name="data">序列化之后的数据</param>
|
||||
public void SendToClient(Socket socket, byte[] data)
|
||||
{
|
||||
//LogOut("准备数据 data=> "+data);
|
||||
SendToSocket(socket, data);
|
||||
}
|
||||
|
||||
#region 事件定义
|
||||
public delegate void OnConnectedHandler(Socket socket);
|
||||
|
||||
public delegate void OnReceiveDataHandler(Socket sk, byte[] data);
|
||||
|
||||
public delegate void OnDisconnectHandler(Socket sk);
|
||||
|
||||
public delegate void OnNetLogHandler(string msg);
|
||||
#endregion
|
||||
|
||||
public event OnConnectedHandler OnConnected;
|
||||
|
||||
public event OnReceiveDataHandler OnReceive;
|
||||
|
||||
public event OnDisconnectHandler OnDisconnected;
|
||||
|
||||
public event OnNetLogHandler OnNetLog;
|
||||
|
||||
/// <summary>
|
||||
/// 做好处理的连接管理
|
||||
/// </summary>
|
||||
private void OnCloseReady(Socket socket)
|
||||
{
|
||||
LogOut("关闭连接");
|
||||
//关闭Socket连接
|
||||
socket.Close();
|
||||
RemoveDictSocket(socket);
|
||||
OnDisconnected?.Invoke(socket);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 主动关闭连接
|
||||
/// </summary>
|
||||
public void CloseConntect(Socket socket)
|
||||
{
|
||||
OnCloseReady(socket);
|
||||
}
|
||||
|
||||
private void DataCallBackReady(Socket socket,byte[] data)
|
||||
{
|
||||
//增加接收计数
|
||||
RevIndex = MaxRevIndexNum;
|
||||
OnReceive(socket,data);
|
||||
}
|
||||
|
||||
private void Recive(object o)
|
||||
{
|
||||
MemoryStream memoryStream = new MemoryStream();//开辟一个内存流
|
||||
var client = o as Socket;
|
||||
//MemoryStream memoryStream = new MemoryStream();//开辟一个内存流
|
||||
|
||||
while (true)
|
||||
{
|
||||
byte[] buffer = new byte[1024 * 1024 * 2];
|
||||
int effective = 0;
|
||||
try
|
||||
{
|
||||
effective = client.Receive(buffer);
|
||||
if (effective == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//远程主机强迫关闭了一个现有的连接
|
||||
OnCloseReady(client);
|
||||
return;
|
||||
//断开连接
|
||||
}
|
||||
if (effective > 0)//如果接受到的消息不为0(不为空)
|
||||
{
|
||||
memoryStream.Write(buffer, 0, effective);//将接受到的数据写入内存流中
|
||||
DataCallBackReady(client, memoryStream.ToArray());
|
||||
//流复用的方式 不用重新new申请
|
||||
memoryStream.Position = 0;
|
||||
memoryStream.SetLength(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void LogOut(string Msg)
|
||||
{
|
||||
//Console.WriteLine(Msg);
|
||||
OnNetLog?.Invoke(Msg);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -1,246 +0,0 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
using static HaoYueNet.ClientNetworkNet4x.BaseData;
|
||||
|
||||
namespace HaoYueNet.ClientNetworkNet4x.OtherMode
|
||||
{
|
||||
public class NetworkHelperCore_SourceMode
|
||||
{
|
||||
private Socket client;
|
||||
|
||||
////响应倒计时计数最大值
|
||||
//private static int MaxRevIndexNum = 6;
|
||||
|
||||
////发送倒计时计数最大值
|
||||
//private static int MaxSendIndexNum = 3;
|
||||
|
||||
//响应倒计时计数最大值
|
||||
private static int MaxRevIndexNum = 50;
|
||||
|
||||
//发送倒计时计数最大值
|
||||
private static int MaxSendIndexNum = 3;
|
||||
|
||||
//响应倒计时计数
|
||||
private static int RevIndex = 0;
|
||||
//发送倒计时计数
|
||||
private static int SendIndex = 0;
|
||||
|
||||
//计时器间隔
|
||||
private static int TimerInterval = 3000;
|
||||
|
||||
public static string LastConnectIP;
|
||||
public static int LastConnectPort;
|
||||
public bool bDetailedLog = false;
|
||||
|
||||
public bool Init(string IP, int port, bool isHadDetailedLog = true, bool bBindReuseAddress = false, int bBindport = 0)
|
||||
{
|
||||
LogOut("==>初始化网络核心");
|
||||
|
||||
bDetailedLog = isHadDetailedLog;
|
||||
RevIndex = MaxRevIndexNum;
|
||||
SendIndex = MaxSendIndexNum;
|
||||
|
||||
client = new Socket(SocketType.Stream, ProtocolType.Tcp);
|
||||
if (bBindReuseAddress)
|
||||
{
|
||||
client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
|
||||
IPEndPoint ipe = new IPEndPoint(IPAddress.Any, Convert.ToInt32(bBindport));
|
||||
client.Bind(ipe);
|
||||
}
|
||||
LastConnectIP = IP;
|
||||
LastConnectPort = port;
|
||||
return Connect(IP, port);
|
||||
}
|
||||
|
||||
bool Connect(string IP, int port)
|
||||
{
|
||||
//带回调的
|
||||
try
|
||||
{
|
||||
if (bDetailedLog)
|
||||
LogOut("连接到远程IP " + IP + ":" + port);
|
||||
else
|
||||
LogOut("连接到远程服务");
|
||||
|
||||
client.Connect(IP, port);
|
||||
Thread thread = new Thread(Recive);
|
||||
thread.IsBackground = true;
|
||||
thread.Start(client);
|
||||
int localport = ((IPEndPoint)client.LocalEndPoint).Port;
|
||||
|
||||
if (bDetailedLog)
|
||||
LogOut($"连接成功!连接到远程IP->{IP}:{port} | 本地端口->{localport}");
|
||||
else
|
||||
LogOut("连接成功!");
|
||||
|
||||
if (bDetailedLog)
|
||||
LogOut("开启心跳包检测");
|
||||
|
||||
OnConnected?.Invoke(true);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (bDetailedLog)
|
||||
LogOut("连接失败:" + ex.ToString());
|
||||
else
|
||||
LogOut("连接失败");
|
||||
|
||||
OnConnected?.Invoke(false);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
~NetworkHelperCore_SourceMode()
|
||||
{
|
||||
client.Close();
|
||||
}
|
||||
|
||||
private void SendToSocket(byte[] data)
|
||||
{
|
||||
//已拼接包长度,这里不再需要拼接长度
|
||||
//data = SendDataWithHead(data);
|
||||
try
|
||||
{
|
||||
SendWithIndex(data);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//连接断开
|
||||
OnCloseReady();
|
||||
return;
|
||||
}
|
||||
//LogOut("发送消息,消息长度=> "+data.Length);
|
||||
}
|
||||
|
||||
private void SendHeartbeat()
|
||||
{
|
||||
try
|
||||
{
|
||||
SendWithIndex(HeartbeatData);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//连接断开
|
||||
OnCloseReady();
|
||||
return;
|
||||
}
|
||||
//LogOut("发送心跳包");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发送数据并计数
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
private void SendWithIndex(byte[] data)
|
||||
{
|
||||
//增加发送计数
|
||||
SendIndex = MaxSendIndexNum;
|
||||
//发送数据
|
||||
client.Send(data);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 供外部调用 发送消息
|
||||
/// </summary>
|
||||
/// <param name="CMDID"></param>
|
||||
/// <param name="data">序列化之后的数据</param>
|
||||
public void SendToServer(byte[] data)
|
||||
{
|
||||
//LogOut("准备数据 data=> "+data);
|
||||
SendToSocket(data);
|
||||
}
|
||||
|
||||
#region 事件定义
|
||||
public delegate void OnReceiveDataHandler(byte[] data);
|
||||
public delegate void OnConnectedHandler(bool IsConnected);
|
||||
public delegate void OnCloseHandler();
|
||||
public delegate void OnLogOutHandler(string Msg);
|
||||
#endregion
|
||||
|
||||
public event OnConnectedHandler OnConnected;
|
||||
public event OnReceiveDataHandler OnReceiveData;
|
||||
public event OnCloseHandler OnClose;
|
||||
/// <summary>
|
||||
/// 网络库调试日志输出
|
||||
/// </summary>
|
||||
public event OnLogOutHandler OnLogOut;
|
||||
|
||||
/// <summary>
|
||||
/// 做好处理的连接管理
|
||||
/// </summary>
|
||||
private void OnCloseReady()
|
||||
{
|
||||
LogOut("关闭连接");
|
||||
//关闭Socket连接
|
||||
client.Close();
|
||||
OnClose?.Invoke();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 主动关闭连接
|
||||
/// </summary>
|
||||
public void CloseConntect()
|
||||
{
|
||||
OnCloseReady();
|
||||
}
|
||||
|
||||
private void DataCallBackReady(byte[] data)
|
||||
{
|
||||
//增加接收计数
|
||||
RevIndex = MaxRevIndexNum;
|
||||
OnReceiveData(data);
|
||||
}
|
||||
|
||||
MemoryStream memoryStream = new MemoryStream();//开辟一个内存流
|
||||
private void Recive(object o)
|
||||
{
|
||||
var client = o as Socket;
|
||||
//MemoryStream memoryStream = new MemoryStream();//开辟一个内存流
|
||||
|
||||
while (true)
|
||||
{
|
||||
byte[] buffer = new byte[1024 * 1024 * 2];
|
||||
int effective = 0;
|
||||
try
|
||||
{
|
||||
effective = client.Receive(buffer);
|
||||
if (effective == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//远程主机强迫关闭了一个现有的连接
|
||||
OnCloseReady();
|
||||
return;
|
||||
//断开连接
|
||||
}
|
||||
if (effective > 0)//如果接受到的消息不为0(不为空)
|
||||
{
|
||||
memoryStream.Write(buffer, 0, effective);//将接受到的数据写入内存流中
|
||||
DataCallBackReady(memoryStream.ToArray());
|
||||
//流复用的方式 不用重新new申请
|
||||
memoryStream.Position = 0;
|
||||
memoryStream.SetLength(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void LogOut(string Msg)
|
||||
{
|
||||
//Console.WriteLine(Msg);
|
||||
OnLogOut?.Invoke(Msg);
|
||||
}
|
||||
|
||||
public Socket GetClientSocket()
|
||||
{
|
||||
return client;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,36 +0,0 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// 有关程序集的一般信息由以下
|
||||
// 控制。更改这些特性值可修改
|
||||
// 与程序集关联的信息。
|
||||
[assembly: AssemblyTitle("HaoYueNet.ClientNetworkNet4x4x4x")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("HaoYueNet.ClientNetworkNet4x4x4x")]
|
||||
[assembly: AssemblyCopyright("Copyright © 2021")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// 将 ComVisible 设置为 false 会使此程序集中的类型
|
||||
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
|
||||
//请将此类型的 ComVisible 特性设置为 true。
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
|
||||
[assembly: Guid("a741610f-29b9-4f0e-9a3d-0b3e1318f031")]
|
||||
|
||||
// 程序集的版本信息由下列四个值组成:
|
||||
//
|
||||
// 主版本
|
||||
// 次版本
|
||||
// 生成号
|
||||
// 修订号
|
||||
//
|
||||
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
|
||||
//通过使用 "*",如下所示:
|
||||
// [assembly: AssemblyVersion("1.0.*")]
|
||||
[assembly: AssemblyVersion("1.0.0.0")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.0")]
|
@ -1,11 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<configuration>
|
||||
<runtime>
|
||||
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral"/>
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.1.2" newVersion="4.0.1.2"/>
|
||||
</dependentAssembly>
|
||||
</assemblyBinding>
|
||||
</runtime>
|
||||
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/></startup></configuration>
|
@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<packages>
|
||||
<package id="System.Buffers" version="4.5.1" targetFramework="net452" />
|
||||
<package id="System.Memory" version="4.5.5" targetFramework="net452" />
|
||||
<package id="System.Runtime.CompilerServices.Unsafe" version="4.5.3" targetFramework="net452" />
|
||||
</packages>
|
@ -1,5 +1,4 @@
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace HaoYueNet.ServerNetwork
|
||||
{
|
||||
public static class BaseData
|
||||
@ -8,21 +7,6 @@ namespace HaoYueNet.ServerNetwork
|
||||
/// 心跳包数据
|
||||
/// </summary>
|
||||
public static byte[] HeartbeatData = new byte[5] { 0x05, 0x00, 0x00, 0x00, 0x00 };
|
||||
|
||||
public static void writeInt(byte[] buf, int offset, int value)
|
||||
{
|
||||
buf[offset++] = (byte)(255 & value);
|
||||
buf[offset++] = (byte)(255 & value >> 8);
|
||||
buf[offset++] = (byte)(255 & value >> 16);
|
||||
buf[offset++] = (byte)(255 & value >>> 24);
|
||||
}
|
||||
|
||||
public static void writeUInt16(byte[] buf, int offset, int value)
|
||||
{
|
||||
buf[offset++] = (byte)(255 & value);
|
||||
buf[offset++] = (byte)(255 & value >> 8);
|
||||
}
|
||||
|
||||
public static class HunterNet_Heartbeat
|
||||
{
|
||||
public static void SetDataToSocketAsyncEventArgs(SocketAsyncEventArgs myreadEventArgs)
|
||||
@ -30,171 +14,58 @@ namespace HaoYueNet.ServerNetwork
|
||||
myreadEventArgs.SetBuffer(HeartbeatData, 0, HeartbeatData.Length);
|
||||
}
|
||||
}
|
||||
|
||||
public static class HunterNet_S2C
|
||||
{
|
||||
public static void SetDataToSocketAsyncEventArgs(SocketAsyncEventArgs myreadEventArgs, UInt16 CmdID, UInt16 Error, byte[] AddonBytes_Data)
|
||||
{
|
||||
myreadEventArgs.SetBuffer(CreatePkgData(CmdID, Error, AddonBytes_Data));
|
||||
}
|
||||
|
||||
public static byte[] CreatePkgData(UInt16 CmdID, UInt16 Error, byte[] AddonBytes_Data)
|
||||
{
|
||||
//byte[] AddonBytes_CmdID = BitConverter.GetBytes(CmdID);
|
||||
//byte[] AddonBytes_Error = BitConverter.GetBytes(Error);
|
||||
//int AllLenght = AddonBytes_CmdID.Length + AddonBytes_Error.Length + AddonBytes_Data.Length + 4;
|
||||
//int LastIndex = 0;
|
||||
////包长度
|
||||
//byte[] AddonBytes_Lenght = BitConverter.GetBytes(AllLenght);
|
||||
|
||||
//byte[] BufferData = new byte[AllLenght];
|
||||
////包长度
|
||||
//AddonBytes_Lenght.CopyTo(BufferData, LastIndex);
|
||||
//LastIndex += AddonBytes_Lenght.Length;
|
||||
|
||||
////CMDID
|
||||
//AddonBytes_CmdID.CopyTo(BufferData, LastIndex);
|
||||
//LastIndex += AddonBytes_CmdID.Length;
|
||||
|
||||
////Error
|
||||
//AddonBytes_Error.CopyTo(BufferData, LastIndex);
|
||||
//LastIndex += AddonBytes_Error.Length;
|
||||
|
||||
////DATA
|
||||
//AddonBytes_Data.CopyTo(BufferData, LastIndex);
|
||||
//LastIndex += AddonBytes_Data.Length;
|
||||
//return BufferData;
|
||||
|
||||
////用Buffer.BlockCopy拷贝
|
||||
//byte[] AddonBytes_CmdID = BitConverter.GetBytes(CmdID);
|
||||
//byte[] AddonBytes_Error = BitConverter.GetBytes(Error);
|
||||
//int AllLenght = AddonBytes_CmdID.Length + AddonBytes_Error.Length + AddonBytes_Data.Length + 4;
|
||||
//int LastIndex = 0;
|
||||
////包长度
|
||||
//byte[] AddonBytes_Lenght = BitConverter.GetBytes(AllLenght);
|
||||
|
||||
//byte[] BufferData = new byte[AllLenght];
|
||||
////包长度
|
||||
//Buffer.BlockCopy(AddonBytes_Lenght, 0, BufferData, LastIndex, AddonBytes_Lenght.Length);
|
||||
//LastIndex += AddonBytes_Lenght.Length;
|
||||
|
||||
////CMDID
|
||||
//Buffer.BlockCopy(AddonBytes_CmdID, 0, BufferData, LastIndex, AddonBytes_CmdID.Length);
|
||||
//LastIndex += AddonBytes_CmdID.Length;
|
||||
|
||||
////Error
|
||||
//Buffer.BlockCopy(AddonBytes_Error, 0, BufferData, LastIndex, AddonBytes_Error.Length);
|
||||
//LastIndex += AddonBytes_Error.Length;
|
||||
|
||||
////DATA
|
||||
//Buffer.BlockCopy(AddonBytes_Data, 0, BufferData, LastIndex, AddonBytes_Data.Length);
|
||||
//LastIndex += AddonBytes_Data.Length;
|
||||
|
||||
|
||||
|
||||
//用Buffer.BlockCopy拷贝
|
||||
//包长度
|
||||
int AllLenght = 4 + 2 + 2 + AddonBytes_Data.Length;
|
||||
byte[] BufferData = new byte[AllLenght];
|
||||
|
||||
//包长度
|
||||
writeInt(BufferData, 0, AllLenght);
|
||||
|
||||
Buffer.BlockCopy(BitConverter.GetBytes(AllLenght), 0, BufferData, 0, sizeof(int));
|
||||
//CMDID
|
||||
writeUInt16(BufferData, 4, CmdID);
|
||||
|
||||
//Error
|
||||
writeUInt16(BufferData, 4 + 2, CmdID);
|
||||
|
||||
Buffer.BlockCopy(BitConverter.GetBytes(CmdID), 0, BufferData, 4, sizeof(UInt16));
|
||||
//ErrID
|
||||
Buffer.BlockCopy(BitConverter.GetBytes(Error), 0, BufferData, 4 + 2, sizeof(UInt16));
|
||||
//DATA
|
||||
Buffer.BlockCopy(AddonBytes_Data, 0, BufferData, 4 + 2 + 2, AddonBytes_Data.Length);
|
||||
|
||||
return BufferData;
|
||||
}
|
||||
|
||||
public static void AnalysisPkgData(Span<byte> srcdata, out UInt16 CmdID, out UInt16 Error, out byte[] data)
|
||||
{
|
||||
//CmdID = BitConverter.ToUInt16(srcdata, 0);
|
||||
//Error = BitConverter.ToUInt16(srcdata, 2);
|
||||
//data = new byte[srcdata.Length - 2 - 2];
|
||||
//Array.Copy(srcdata, 4, data, 0, data.Length);
|
||||
|
||||
//CmdID = BitConverter.ToUInt16(srcdata, 0);
|
||||
//Error = BitConverter.ToUInt16(srcdata, 2);
|
||||
//Span<byte> span_srcdata = srcdata;
|
||||
//data = span_srcdata.Slice(2 + 2).ToArray();
|
||||
|
||||
CmdID = BitConverter.ToUInt16(srcdata.Slice(0, 2));
|
||||
Error = BitConverter.ToUInt16(srcdata.Slice(2, 2));
|
||||
data = srcdata.Slice(2 + 2).ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
public static class HunterNet_C2S
|
||||
{
|
||||
public static void SetDataToSocketAsyncEventArgs(SocketAsyncEventArgs myreadEventArgs, UInt16 CmdID, byte[] AddonBytes_Data)
|
||||
{
|
||||
myreadEventArgs.SetBuffer(CreatePkgData(CmdID, AddonBytes_Data));
|
||||
}
|
||||
|
||||
public static byte[] CreatePkgData(UInt16 CmdID, byte[] AddonBytes_Data)
|
||||
{
|
||||
//byte[] AddonBytes_CmdID = BitConverter.GetBytes(CmdID);
|
||||
//int AllLenght = AddonBytes_CmdID.Length + AddonBytes_Data.Length + 4;
|
||||
//int LastIndex = 0;
|
||||
////包长度
|
||||
//byte[] AddonBytes_Lenght = BitConverter.GetBytes(AllLenght);
|
||||
|
||||
//byte[] BufferData = new byte[AllLenght];
|
||||
|
||||
////包长度
|
||||
//AddonBytes_Lenght.CopyTo(BufferData, LastIndex);
|
||||
//LastIndex += AddonBytes_Lenght.Length;
|
||||
|
||||
////CMDID
|
||||
//AddonBytes_CmdID.CopyTo(BufferData, LastIndex);
|
||||
//LastIndex += AddonBytes_CmdID.Length;
|
||||
|
||||
////DATA
|
||||
//AddonBytes_Data.CopyTo(BufferData, LastIndex);
|
||||
//LastIndex += AddonBytes_Data.Length;
|
||||
|
||||
//myreadEventArgs.SetBuffer(BufferData, 0, BufferData.Length);
|
||||
//return BufferData;
|
||||
|
||||
//用Buffer.BlockCopy拷贝
|
||||
|
||||
byte[] AddonBytes_CmdID = BitConverter.GetBytes(CmdID);
|
||||
int AllLenght = AddonBytes_CmdID.Length + AddonBytes_Data.Length + 4;
|
||||
int LastIndex = 0;
|
||||
//包长度
|
||||
byte[] AddonBytes_Lenght = BitConverter.GetBytes(AllLenght);
|
||||
|
||||
byte[] BufferData = new byte[AllLenght];
|
||||
//包长度
|
||||
Buffer.BlockCopy(AddonBytes_Lenght, 0, BufferData, LastIndex, AddonBytes_Lenght.Length);
|
||||
LastIndex += AddonBytes_Lenght.Length;
|
||||
|
||||
Buffer.BlockCopy(AddonBytes_Lenght, 0, BufferData, 0, AddonBytes_Lenght.Length);
|
||||
//CMDID
|
||||
Buffer.BlockCopy(AddonBytes_CmdID, 0, BufferData, LastIndex, AddonBytes_CmdID.Length);
|
||||
LastIndex += AddonBytes_CmdID.Length;
|
||||
|
||||
Buffer.BlockCopy(AddonBytes_CmdID, 0, BufferData, 4, AddonBytes_CmdID.Length);
|
||||
//DATA
|
||||
Buffer.BlockCopy(AddonBytes_Data, 0, BufferData, LastIndex, AddonBytes_Data.Length);
|
||||
LastIndex += AddonBytes_Data.Length;
|
||||
Buffer.BlockCopy(AddonBytes_Data, 0, BufferData, 4 + 2, AddonBytes_Data.Length);
|
||||
return BufferData;
|
||||
}
|
||||
|
||||
public static void AnalysisPkgData(Span<byte> srcdata, out UInt16 CmdID, out byte[] data)
|
||||
{
|
||||
//data = new byte[srcdata.Length - 2];
|
||||
//CmdID = BitConverter.ToUInt16(srcdata, 0);
|
||||
//Array.Copy(srcdata, 2, data, 0, data.Length);
|
||||
|
||||
//CmdID = BitConverter.ToUInt16(srcdata, 0);
|
||||
//Span<byte> span_srcdata = srcdata;
|
||||
//data = span_srcdata.Slice(2).ToArray();
|
||||
|
||||
CmdID = BitConverter.ToUInt16(srcdata.Slice(0, 2));
|
||||
data = srcdata.Slice(2).ToArray();
|
||||
}
|
||||
|
@ -30,16 +30,10 @@ namespace HaoYueNet.ServerNetwork
|
||||
/// </summary>
|
||||
public object UserInfo { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 数据缓存区
|
||||
/// </summary>
|
||||
//public List<byte> Buffer { get; set; }
|
||||
|
||||
public MemoryStream memoryStream { get; set; }
|
||||
|
||||
public AsyncUserToken()
|
||||
{
|
||||
//this.Buffer = new List<byte>();
|
||||
this.memoryStream = new MemoryStream();
|
||||
}
|
||||
/// <summary>
|
||||
|
@ -1,8 +1,5 @@
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace HaoYueNet.ServerNetwork
|
||||
namespace HaoYueNet.ServerNetwork
|
||||
{
|
||||
|
||||
public class MemoryStreamPool
|
||||
{
|
||||
Stack<MemoryStream> m_pool;
|
||||
|
@ -2,7 +2,6 @@
|
||||
|
||||
namespace HaoYueNet.ServerNetwork
|
||||
{
|
||||
|
||||
public class SocketEventPool
|
||||
{
|
||||
Stack<SocketAsyncEventArgs> m_pool;
|
||||
|
@ -1,6 +1,4 @@
|
||||
//using HunterProtobufCore;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using static HaoYueNet.ServerNetwork.BaseData;
|
||||
|
||||
@ -231,7 +229,11 @@ namespace HaoYueNet.ServerNetwork
|
||||
#region Token管理
|
||||
public AsyncUserToken GetAsyncUserTokenForSocket(Socket sk)
|
||||
{
|
||||
return _DictSocketAsyncUserToken.ContainsKey(sk) ? _DictSocketAsyncUserToken[sk] : null;
|
||||
AsyncUserToken result;
|
||||
if (_DictSocketAsyncUserToken.TryGetValue(sk,out result))
|
||||
return result;
|
||||
return null;
|
||||
//return _DictSocketAsyncUserToken.ContainsKey(sk) ? _DictSocketAsyncUserToken[sk] : null;
|
||||
}
|
||||
void AddUserToken(AsyncUserToken userToken)
|
||||
{
|
||||
@ -373,47 +375,32 @@ namespace HaoYueNet.ServerNetwork
|
||||
{
|
||||
try
|
||||
{
|
||||
// check if the remote host closed the connection
|
||||
AsyncUserToken token = (AsyncUserToken)e.UserToken;
|
||||
if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
|
||||
{
|
||||
//读取数据
|
||||
//byte[] data = new byte[e.BytesTransferred];
|
||||
//Array.Copy(e.Buffer, e.Offset, data, 0, e.BytesTransferred);
|
||||
//lock (token.Buffer)
|
||||
lock(token.memoryStream)
|
||||
{
|
||||
//token.Buffer.AddRange(data);
|
||||
token.memoryStream.Write(e.Buffer, e.Offset, e.BytesTransferred);
|
||||
do
|
||||
{
|
||||
|
||||
//DataCallBackReady(token, data);
|
||||
////从数据池中移除这组数据
|
||||
//lock (token.Buffer)
|
||||
//{
|
||||
// token.Buffer.Clear();
|
||||
//}
|
||||
|
||||
DataCallBackReady(token, token.memoryStream.ToArray());
|
||||
//流复用的方式 不用重新new申请
|
||||
token.memoryStream.Position = 0;
|
||||
token.memoryStream.SetLength(0);
|
||||
|
||||
//这里API处理完后,并没有返回结果,当然结果是要返回的,却不是在这里, 这里的代码只管接收.
|
||||
//若要返回结果,可在API处理中调用此类对象的SendMessage方法,统一打包发送.不要被微软的示例给迷惑了.
|
||||
} while (token.memoryStream.Length > 0);
|
||||
//} while (token.Buffer.Count > 4);
|
||||
}
|
||||
|
||||
//继续接收. 为什么要这么写,请看Socket.ReceiveAsync方法的说明
|
||||
if (!token.Socket.ReceiveAsync(e))
|
||||
{
|
||||
this.ProcessReceive(e);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
//清理数据
|
||||
token.memoryStream.SetLength(0);
|
||||
token.memoryStream.Seek(0, SeekOrigin.Begin);
|
||||
CloseClientSocket(e);
|
||||
}
|
||||
}
|
||||
@ -620,58 +607,5 @@ namespace HaoYueNet.ServerNetwork
|
||||
OnNetLog?.Invoke(msg);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 心跳包
|
||||
/*
|
||||
/// <summary>
|
||||
/// 发送心跳包
|
||||
/// </summary>
|
||||
/// <param name="sk"></param>
|
||||
///
|
||||
private void SendHeartbeatWithIndex(AsyncUserToken token)
|
||||
{
|
||||
if (token == null || token.Socket == null || !token.Socket.Connected)
|
||||
return;
|
||||
try
|
||||
{
|
||||
//OutNetLog(DateTime.Now.ToString() + "发送心跳包");
|
||||
token.SendIndex = MaxSendIndexNum;
|
||||
SendHeartbeatMessage(token);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
CloseReady(token);
|
||||
}
|
||||
}
|
||||
/// <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)
|
||||
{
|
||||
//判定掉线
|
||||
CloseReady(m_clients[i]);
|
||||
return;
|
||||
}
|
||||
|
||||
//发送计数
|
||||
m_clients[i].SendIndex--;
|
||||
if (m_clients[i].SendIndex <= 0)//需要发送心跳包了
|
||||
{
|
||||
//重置倒计时计数
|
||||
m_clients[i].SendIndex = MaxSendIndexNum;
|
||||
SendHeartbeatWithIndex(m_clients[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
@ -1,10 +1,4 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
|
||||
namespace HaoYueNet.ServerNetwork
|
||||
namespace HaoYueNet.ServerNetwork
|
||||
{
|
||||
public class TokenWithMsg_SourceMode
|
||||
{
|
||||
@ -15,7 +9,6 @@ namespace HaoYueNet.ServerNetwork
|
||||
|
||||
public class TokenMsgPool_SourceMode
|
||||
{
|
||||
//Stack<TokenWithMsg> msg_pool;
|
||||
Queue<TokenWithMsg_SourceMode> msg_pool;
|
||||
|
||||
public TokenMsgPool_SourceMode(int capacity)
|
||||
|
@ -1,5 +1,5 @@
|
||||
//using HunterProtobufCore;
|
||||
using System.IO;
|
||||
using System.Buffers;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using static HaoYueNet.ServerNetwork.BaseData;
|
||||
@ -231,7 +231,11 @@ namespace HaoYueNet.ServerNetwork
|
||||
#region Token管理
|
||||
public AsyncUserToken GetAsyncUserTokenForSocket(Socket sk)
|
||||
{
|
||||
return _DictSocketAsyncUserToken.ContainsKey(sk) ? _DictSocketAsyncUserToken[sk] : null;
|
||||
AsyncUserToken result;
|
||||
if (_DictSocketAsyncUserToken.TryGetValue(sk, out result))
|
||||
return result;
|
||||
return null;
|
||||
//return _DictSocketAsyncUserToken.ContainsKey(sk) ? _DictSocketAsyncUserToken[sk] : null;
|
||||
}
|
||||
void AddUserToken(AsyncUserToken userToken)
|
||||
{
|
||||
@ -374,86 +378,67 @@ namespace HaoYueNet.ServerNetwork
|
||||
{
|
||||
try
|
||||
{
|
||||
// check if the remote host closed the connection
|
||||
AsyncUserToken token = (AsyncUserToken)e.UserToken;
|
||||
if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
|
||||
{
|
||||
//读取数据
|
||||
//byte[] data = new byte[e.BytesTransferred];
|
||||
//Array.Copy(e.Buffer, e.Offset, data, 0, e.BytesTransferred);
|
||||
//lock (token.Buffer)
|
||||
lock(token.memoryStream)
|
||||
{
|
||||
//token.Buffer.AddRange(data);
|
||||
token.memoryStream.Write(e.Buffer, e.Offset, e.BytesTransferred);
|
||||
do
|
||||
{
|
||||
//如果包头不完整
|
||||
//if (token.Buffer.Count < 4)
|
||||
if (token.memoryStream.Length < 4)
|
||||
break;
|
||||
|
||||
////判断包的长度
|
||||
//byte[] lenBytes = token.Buffer.GetRange(0, 4).ToArray();
|
||||
//int packageLen = BitConverter.ToInt32(lenBytes, 0) - 4;
|
||||
//if (packageLen > token.Buffer.Count - 4)
|
||||
//{ //长度不够时,退出循环,让程序继续接收
|
||||
// break;
|
||||
//}
|
||||
|
||||
if (token.memoryStream.Length < 4) break;//包头不完整,继续接收
|
||||
long FristBeginPos = token.memoryStream.Position;
|
||||
byte[] lenBytes = new byte[4];
|
||||
|
||||
//从Byte池申请
|
||||
byte[] lenBytes = ArrayPool<byte>.Shared.Rent(4);
|
||||
|
||||
token.memoryStream.Seek(0, SeekOrigin.Begin);
|
||||
token.memoryStream.Read(lenBytes, 0, 4);
|
||||
int packageLen = BitConverter.ToInt32(lenBytes, 0) - 4;
|
||||
|
||||
//归还byte[]
|
||||
ArrayPool<byte>.Shared.Return(lenBytes);
|
||||
|
||||
if (packageLen > token.memoryStream.Length - 4)
|
||||
{
|
||||
token.memoryStream.Seek(FristBeginPos, SeekOrigin.Begin);
|
||||
//长度不够时,退出循环,让程序继续接收
|
||||
break;
|
||||
break;//长度不够时,退出循环,让程序继续接收
|
||||
}
|
||||
|
||||
////包够长时,则提取出来,交给后面的程序去处理
|
||||
//byte[] rev = token.Buffer.GetRange(4, packageLen).ToArray();
|
||||
//申请byte池 一定要记得回收!!
|
||||
byte[] rev_fromArrayPool = ArrayPool<byte>.Shared.Rent(packageLen);
|
||||
|
||||
byte[] rev = new byte[packageLen];
|
||||
token.memoryStream.Seek(4, SeekOrigin.Begin);
|
||||
token.memoryStream.Read(rev, 0, packageLen);
|
||||
|
||||
//从数据池中移除这组数据
|
||||
//lock (token.Buffer)
|
||||
//{
|
||||
// token.Buffer.RemoveRange(0, packageLen + 4);
|
||||
//}
|
||||
|
||||
token.memoryStream.Read(rev_fromArrayPool, 0, packageLen);
|
||||
token.memoryStream.Seek(FristBeginPos, SeekOrigin.Begin);
|
||||
//从数据池中移除这组数据
|
||||
lock (token.memoryStream)
|
||||
{
|
||||
//token.memoryStream.Position = 0;
|
||||
//token.memoryStream.SetLength(0);
|
||||
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);
|
||||
}
|
||||
|
||||
DataCallBackReady(token, rev);
|
||||
//用Span内存切片,因为来自ArrayPool的byte长度,可能大于本身申请的长度
|
||||
Span<byte> rev_span = rev_fromArrayPool;
|
||||
rev_span = rev_span.Slice(0, packageLen);
|
||||
DataCallBackReady(token, rev_span);
|
||||
|
||||
//这里API处理完后,并没有返回结果,当然结果是要返回的,却不是在这里, 这里的代码只管接收.
|
||||
//若要返回结果,可在API处理中调用此类对象的SendMessage方法,统一打包发送.不要被微软的示例给迷惑了.
|
||||
//} while (token.Buffer.Count > 4);
|
||||
//回收(这里依赖DataCallBackReady中,有一次数据拷贝,这个后续还要进一步精进性能优化,否则不能在这里回收,否则影响业务层)
|
||||
ArrayPool<byte>.Shared.Return(rev_fromArrayPool);
|
||||
} while (token.memoryStream.Length > 4);
|
||||
}
|
||||
|
||||
//继续接收. 为什么要这么写,请看Socket.ReceiveAsync方法的说明
|
||||
//如果返回为False则代表此刻已经完成,不必等待完成端口回调,则直接调用ProcessReceive
|
||||
if (!token.Socket.ReceiveAsync(e))
|
||||
{
|
||||
this.ProcessReceive(e);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
//清理数据
|
||||
token.memoryStream.SetLength(0);
|
||||
token.memoryStream.Seek(0, SeekOrigin.Begin);
|
||||
CloseClientSocket(e);
|
||||
}
|
||||
}
|
||||
@ -478,8 +463,6 @@ namespace HaoYueNet.ServerNetwork
|
||||
}
|
||||
void IO_Completed(object sender, SocketAsyncEventArgs e)
|
||||
{
|
||||
// determine which type of operation just completed and call the associated handler
|
||||
|
||||
switch (e.LastOperation)
|
||||
{
|
||||
case SocketAsyncOperation.Receive:
|
||||
@ -650,7 +633,7 @@ namespace HaoYueNet.ServerNetwork
|
||||
#endregion
|
||||
|
||||
#region 处理前预备
|
||||
private void DataCallBackReady(AsyncUserToken sk, byte[] data)
|
||||
private void DataCallBackReady(AsyncUserToken sk, Span<byte> data)
|
||||
{
|
||||
//增加接收计数
|
||||
sk.RevIndex = MaxRevIndexNum;
|
||||
|
@ -1,506 +0,0 @@
|
||||
//// <auto-generated>
|
||||
//// Generated by the protocol buffer compiler. DO NOT EDIT!
|
||||
//// source: protobuf_HunterNetCore.proto
|
||||
//// </auto-generated>
|
||||
//#pragma warning disable 1591, 0612, 3021
|
||||
//#region Designer generated code
|
||||
|
||||
//using pb = global::Google.Protobuf;
|
||||
//using pbc = global::Google.Protobuf.Collections;
|
||||
//using pbr = global::Google.Protobuf.Reflection;
|
||||
//using scg = global::System.Collections.Generic;
|
||||
//namespace HunterProtobufCore {
|
||||
|
||||
// /// <summary>Holder for reflection information generated from protobuf_HunterNetCore.proto</summary>
|
||||
// public static partial class ProtobufHunterNetCoreReflection {
|
||||
|
||||
// #region Descriptor
|
||||
// /// <summary>File descriptor for protobuf_HunterNetCore.proto</summary>
|
||||
// public static pbr::FileDescriptor Descriptor {
|
||||
// get { return descriptor; }
|
||||
// }
|
||||
// private static pbr::FileDescriptor descriptor;
|
||||
|
||||
// static ProtobufHunterNetCoreReflection() {
|
||||
// byte[] descriptorData = global::System.Convert.FromBase64String(
|
||||
// string.Concat(
|
||||
// "Chxwcm90b2J1Zl9IdW50ZXJOZXRDb3JlLnByb3RvEhJIdW50ZXJQcm90b2J1",
|
||||
// "ZkNvcmUiSAoNSHVudGVyTmV0X0MyUxIbChNIdW50ZXJOZXRDb3JlX0NtZElE",
|
||||
// "GAEgASgFEhoKEkh1bnRlck5ldENvcmVfRGF0YRgCIAEoDCJpCg1IdW50ZXJO",
|
||||
// "ZXRfUzJDEhsKE0h1bnRlck5ldENvcmVfQ21kSUQYASABKAUSHwoXSHVudGVy",
|
||||
// "TmV0Q29yZV9FUlJPUkNvZGUYAiABKAUSGgoSSHVudGVyTmV0Q29yZV9EYXRh",
|
||||
// "GAMgASgMQgJIAWIGcHJvdG8z"));
|
||||
// descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
|
||||
// new pbr::FileDescriptor[] { },
|
||||
// new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
|
||||
// new pbr::GeneratedClrTypeInfo(typeof(global::HunterProtobufCore.HunterNet_C2S), global::HunterProtobufCore.HunterNet_C2S.Parser, new[]{ "HunterNetCoreCmdID", "HunterNetCoreData" }, null, null, null, null),
|
||||
// new pbr::GeneratedClrTypeInfo(typeof(global::HunterProtobufCore.HunterNet_S2C), global::HunterProtobufCore.HunterNet_S2C.Parser, new[]{ "HunterNetCoreCmdID", "HunterNetCoreERRORCode", "HunterNetCoreData" }, null, null, null, null)
|
||||
// }));
|
||||
// }
|
||||
// #endregion
|
||||
|
||||
// }
|
||||
// #region Messages
|
||||
// /// <summary>
|
||||
// ///上行
|
||||
// /// </summary>
|
||||
// public sealed partial class HunterNet_C2S : pb::IMessage<HunterNet_C2S>
|
||||
// #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
|
||||
// , pb::IBufferMessage
|
||||
// #endif
|
||||
// {
|
||||
// private static readonly pb::MessageParser<HunterNet_C2S> _parser = new pb::MessageParser<HunterNet_C2S>(() => new HunterNet_C2S());
|
||||
// private pb::UnknownFieldSet _unknownFields;
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public static pb::MessageParser<HunterNet_C2S> Parser { get { return _parser; } }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public static pbr::MessageDescriptor Descriptor {
|
||||
// get { return global::HunterProtobufCore.ProtobufHunterNetCoreReflection.Descriptor.MessageTypes[0]; }
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// pbr::MessageDescriptor pb::IMessage.Descriptor {
|
||||
// get { return Descriptor; }
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public HunterNet_C2S() {
|
||||
// OnConstruction();
|
||||
// }
|
||||
|
||||
// partial void OnConstruction();
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public HunterNet_C2S(HunterNet_C2S other) : this() {
|
||||
// hunterNetCoreCmdID_ = other.hunterNetCoreCmdID_;
|
||||
// hunterNetCoreData_ = other.hunterNetCoreData_;
|
||||
// _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public HunterNet_C2S Clone() {
|
||||
// return new HunterNet_C2S(this);
|
||||
// }
|
||||
|
||||
// /// <summary>Field number for the "HunterNetCore_CmdID" field.</summary>
|
||||
// public const int HunterNetCoreCmdIDFieldNumber = 1;
|
||||
// private int hunterNetCoreCmdID_;
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public int HunterNetCoreCmdID {
|
||||
// get { return hunterNetCoreCmdID_; }
|
||||
// set {
|
||||
// hunterNetCoreCmdID_ = value;
|
||||
// }
|
||||
// }
|
||||
|
||||
// /// <summary>Field number for the "HunterNetCore_Data" field.</summary>
|
||||
// public const int HunterNetCoreDataFieldNumber = 2;
|
||||
// private pb::ByteString hunterNetCoreData_ = pb::ByteString.Empty;
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public pb::ByteString HunterNetCoreData {
|
||||
// get { return hunterNetCoreData_; }
|
||||
// set {
|
||||
// hunterNetCoreData_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
|
||||
// }
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public override bool Equals(object other) {
|
||||
// return Equals(other as HunterNet_C2S);
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public bool Equals(HunterNet_C2S other) {
|
||||
// if (ReferenceEquals(other, null)) {
|
||||
// return false;
|
||||
// }
|
||||
// if (ReferenceEquals(other, this)) {
|
||||
// return true;
|
||||
// }
|
||||
// if (HunterNetCoreCmdID != other.HunterNetCoreCmdID) return false;
|
||||
// if (HunterNetCoreData != other.HunterNetCoreData) return false;
|
||||
// return Equals(_unknownFields, other._unknownFields);
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public override int GetHashCode() {
|
||||
// int hash = 1;
|
||||
// if (HunterNetCoreCmdID != 0) hash ^= HunterNetCoreCmdID.GetHashCode();
|
||||
// if (HunterNetCoreData.Length != 0) hash ^= HunterNetCoreData.GetHashCode();
|
||||
// if (_unknownFields != null) {
|
||||
// hash ^= _unknownFields.GetHashCode();
|
||||
// }
|
||||
// return hash;
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public override string ToString() {
|
||||
// return pb::JsonFormatter.ToDiagnosticString(this);
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public void WriteTo(pb::CodedOutputStream output) {
|
||||
// #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
|
||||
// output.WriteRawMessage(this);
|
||||
// #else
|
||||
// if (HunterNetCoreCmdID != 0) {
|
||||
// output.WriteRawTag(8);
|
||||
// output.WriteInt32(HunterNetCoreCmdID);
|
||||
// }
|
||||
// if (HunterNetCoreData.Length != 0) {
|
||||
// output.WriteRawTag(18);
|
||||
// output.WriteBytes(HunterNetCoreData);
|
||||
// }
|
||||
// if (_unknownFields != null) {
|
||||
// _unknownFields.WriteTo(output);
|
||||
// }
|
||||
// #endif
|
||||
// }
|
||||
|
||||
// #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
|
||||
// if (HunterNetCoreCmdID != 0) {
|
||||
// output.WriteRawTag(8);
|
||||
// output.WriteInt32(HunterNetCoreCmdID);
|
||||
// }
|
||||
// if (HunterNetCoreData.Length != 0) {
|
||||
// output.WriteRawTag(18);
|
||||
// output.WriteBytes(HunterNetCoreData);
|
||||
// }
|
||||
// if (_unknownFields != null) {
|
||||
// _unknownFields.WriteTo(ref output);
|
||||
// }
|
||||
// }
|
||||
// #endif
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public int CalculateSize() {
|
||||
// int size = 0;
|
||||
// if (HunterNetCoreCmdID != 0) {
|
||||
// size += 1 + pb::CodedOutputStream.ComputeInt32Size(HunterNetCoreCmdID);
|
||||
// }
|
||||
// if (HunterNetCoreData.Length != 0) {
|
||||
// size += 1 + pb::CodedOutputStream.ComputeBytesSize(HunterNetCoreData);
|
||||
// }
|
||||
// if (_unknownFields != null) {
|
||||
// size += _unknownFields.CalculateSize();
|
||||
// }
|
||||
// return size;
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public void MergeFrom(HunterNet_C2S other) {
|
||||
// if (other == null) {
|
||||
// return;
|
||||
// }
|
||||
// if (other.HunterNetCoreCmdID != 0) {
|
||||
// HunterNetCoreCmdID = other.HunterNetCoreCmdID;
|
||||
// }
|
||||
// if (other.HunterNetCoreData.Length != 0) {
|
||||
// HunterNetCoreData = other.HunterNetCoreData;
|
||||
// }
|
||||
// _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public void MergeFrom(pb::CodedInputStream input) {
|
||||
// #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
|
||||
// input.ReadRawMessage(this);
|
||||
// #else
|
||||
// uint tag;
|
||||
// while ((tag = input.ReadTag()) != 0) {
|
||||
// switch(tag) {
|
||||
// default:
|
||||
// _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
|
||||
// break;
|
||||
// case 8: {
|
||||
// HunterNetCoreCmdID = input.ReadInt32();
|
||||
// break;
|
||||
// }
|
||||
// case 18: {
|
||||
// HunterNetCoreData = input.ReadBytes();
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// #endif
|
||||
// }
|
||||
|
||||
// #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
|
||||
// uint tag;
|
||||
// while ((tag = input.ReadTag()) != 0) {
|
||||
// switch(tag) {
|
||||
// default:
|
||||
// _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
|
||||
// break;
|
||||
// case 8: {
|
||||
// HunterNetCoreCmdID = input.ReadInt32();
|
||||
// break;
|
||||
// }
|
||||
// case 18: {
|
||||
// HunterNetCoreData = input.ReadBytes();
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// #endif
|
||||
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// ///下行
|
||||
// /// </summary>
|
||||
// public sealed partial class HunterNet_S2C : pb::IMessage<HunterNet_S2C>
|
||||
// #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
|
||||
// , pb::IBufferMessage
|
||||
// #endif
|
||||
// {
|
||||
// private static readonly pb::MessageParser<HunterNet_S2C> _parser = new pb::MessageParser<HunterNet_S2C>(() => new HunterNet_S2C());
|
||||
// private pb::UnknownFieldSet _unknownFields;
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public static pb::MessageParser<HunterNet_S2C> Parser { get { return _parser; } }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public static pbr::MessageDescriptor Descriptor {
|
||||
// get { return global::HunterProtobufCore.ProtobufHunterNetCoreReflection.Descriptor.MessageTypes[1]; }
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// pbr::MessageDescriptor pb::IMessage.Descriptor {
|
||||
// get { return Descriptor; }
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public HunterNet_S2C() {
|
||||
// OnConstruction();
|
||||
// }
|
||||
|
||||
// partial void OnConstruction();
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public HunterNet_S2C(HunterNet_S2C other) : this() {
|
||||
// hunterNetCoreCmdID_ = other.hunterNetCoreCmdID_;
|
||||
// hunterNetCoreERRORCode_ = other.hunterNetCoreERRORCode_;
|
||||
// hunterNetCoreData_ = other.hunterNetCoreData_;
|
||||
// _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public HunterNet_S2C Clone() {
|
||||
// return new HunterNet_S2C(this);
|
||||
// }
|
||||
|
||||
// /// <summary>Field number for the "HunterNetCore_CmdID" field.</summary>
|
||||
// public const int HunterNetCoreCmdIDFieldNumber = 1;
|
||||
// private int hunterNetCoreCmdID_;
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public int HunterNetCoreCmdID {
|
||||
// get { return hunterNetCoreCmdID_; }
|
||||
// set {
|
||||
// hunterNetCoreCmdID_ = value;
|
||||
// }
|
||||
// }
|
||||
|
||||
// /// <summary>Field number for the "HunterNetCore_ERRORCode" field.</summary>
|
||||
// public const int HunterNetCoreERRORCodeFieldNumber = 2;
|
||||
// private int hunterNetCoreERRORCode_;
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public int HunterNetCoreERRORCode {
|
||||
// get { return hunterNetCoreERRORCode_; }
|
||||
// set {
|
||||
// hunterNetCoreERRORCode_ = value;
|
||||
// }
|
||||
// }
|
||||
|
||||
// /// <summary>Field number for the "HunterNetCore_Data" field.</summary>
|
||||
// public const int HunterNetCoreDataFieldNumber = 3;
|
||||
// private pb::ByteString hunterNetCoreData_ = pb::ByteString.Empty;
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public pb::ByteString HunterNetCoreData {
|
||||
// get { return hunterNetCoreData_; }
|
||||
// set {
|
||||
// hunterNetCoreData_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
|
||||
// }
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public override bool Equals(object other) {
|
||||
// return Equals(other as HunterNet_S2C);
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public bool Equals(HunterNet_S2C other) {
|
||||
// if (ReferenceEquals(other, null)) {
|
||||
// return false;
|
||||
// }
|
||||
// if (ReferenceEquals(other, this)) {
|
||||
// return true;
|
||||
// }
|
||||
// if (HunterNetCoreCmdID != other.HunterNetCoreCmdID) return false;
|
||||
// if (HunterNetCoreERRORCode != other.HunterNetCoreERRORCode) return false;
|
||||
// if (HunterNetCoreData != other.HunterNetCoreData) return false;
|
||||
// return Equals(_unknownFields, other._unknownFields);
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public override int GetHashCode() {
|
||||
// int hash = 1;
|
||||
// if (HunterNetCoreCmdID != 0) hash ^= HunterNetCoreCmdID.GetHashCode();
|
||||
// if (HunterNetCoreERRORCode != 0) hash ^= HunterNetCoreERRORCode.GetHashCode();
|
||||
// if (HunterNetCoreData.Length != 0) hash ^= HunterNetCoreData.GetHashCode();
|
||||
// if (_unknownFields != null) {
|
||||
// hash ^= _unknownFields.GetHashCode();
|
||||
// }
|
||||
// return hash;
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public override string ToString() {
|
||||
// return pb::JsonFormatter.ToDiagnosticString(this);
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public void WriteTo(pb::CodedOutputStream output) {
|
||||
// #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
|
||||
// output.WriteRawMessage(this);
|
||||
// #else
|
||||
// if (HunterNetCoreCmdID != 0) {
|
||||
// output.WriteRawTag(8);
|
||||
// output.WriteInt32(HunterNetCoreCmdID);
|
||||
// }
|
||||
// if (HunterNetCoreERRORCode != 0) {
|
||||
// output.WriteRawTag(16);
|
||||
// output.WriteInt32(HunterNetCoreERRORCode);
|
||||
// }
|
||||
// if (HunterNetCoreData.Length != 0) {
|
||||
// output.WriteRawTag(26);
|
||||
// output.WriteBytes(HunterNetCoreData);
|
||||
// }
|
||||
// if (_unknownFields != null) {
|
||||
// _unknownFields.WriteTo(output);
|
||||
// }
|
||||
// #endif
|
||||
// }
|
||||
|
||||
// #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
|
||||
// if (HunterNetCoreCmdID != 0) {
|
||||
// output.WriteRawTag(8);
|
||||
// output.WriteInt32(HunterNetCoreCmdID);
|
||||
// }
|
||||
// if (HunterNetCoreERRORCode != 0) {
|
||||
// output.WriteRawTag(16);
|
||||
// output.WriteInt32(HunterNetCoreERRORCode);
|
||||
// }
|
||||
// if (HunterNetCoreData.Length != 0) {
|
||||
// output.WriteRawTag(26);
|
||||
// output.WriteBytes(HunterNetCoreData);
|
||||
// }
|
||||
// if (_unknownFields != null) {
|
||||
// _unknownFields.WriteTo(ref output);
|
||||
// }
|
||||
// }
|
||||
// #endif
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public int CalculateSize() {
|
||||
// int size = 0;
|
||||
// if (HunterNetCoreCmdID != 0) {
|
||||
// size += 1 + pb::CodedOutputStream.ComputeInt32Size(HunterNetCoreCmdID);
|
||||
// }
|
||||
// if (HunterNetCoreERRORCode != 0) {
|
||||
// size += 1 + pb::CodedOutputStream.ComputeInt32Size(HunterNetCoreERRORCode);
|
||||
// }
|
||||
// if (HunterNetCoreData.Length != 0) {
|
||||
// size += 1 + pb::CodedOutputStream.ComputeBytesSize(HunterNetCoreData);
|
||||
// }
|
||||
// if (_unknownFields != null) {
|
||||
// size += _unknownFields.CalculateSize();
|
||||
// }
|
||||
// return size;
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public void MergeFrom(HunterNet_S2C other) {
|
||||
// if (other == null) {
|
||||
// return;
|
||||
// }
|
||||
// if (other.HunterNetCoreCmdID != 0) {
|
||||
// HunterNetCoreCmdID = other.HunterNetCoreCmdID;
|
||||
// }
|
||||
// if (other.HunterNetCoreERRORCode != 0) {
|
||||
// HunterNetCoreERRORCode = other.HunterNetCoreERRORCode;
|
||||
// }
|
||||
// if (other.HunterNetCoreData.Length != 0) {
|
||||
// HunterNetCoreData = other.HunterNetCoreData;
|
||||
// }
|
||||
// _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public void MergeFrom(pb::CodedInputStream input) {
|
||||
// #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
|
||||
// input.ReadRawMessage(this);
|
||||
// #else
|
||||
// uint tag;
|
||||
// while ((tag = input.ReadTag()) != 0) {
|
||||
// switch(tag) {
|
||||
// default:
|
||||
// _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
|
||||
// break;
|
||||
// case 8: {
|
||||
// HunterNetCoreCmdID = input.ReadInt32();
|
||||
// break;
|
||||
// }
|
||||
// case 16: {
|
||||
// HunterNetCoreERRORCode = input.ReadInt32();
|
||||
// break;
|
||||
// }
|
||||
// case 26: {
|
||||
// HunterNetCoreData = input.ReadBytes();
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// #endif
|
||||
// }
|
||||
|
||||
// #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
|
||||
// uint tag;
|
||||
// while ((tag = input.ReadTag()) != 0) {
|
||||
// switch(tag) {
|
||||
// default:
|
||||
// _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
|
||||
// break;
|
||||
// case 8: {
|
||||
// HunterNetCoreCmdID = input.ReadInt32();
|
||||
// break;
|
||||
// }
|
||||
// case 16: {
|
||||
// HunterNetCoreERRORCode = input.ReadInt32();
|
||||
// break;
|
||||
// }
|
||||
// case 26: {
|
||||
// HunterNetCoreData = input.ReadBytes();
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// #endif
|
||||
|
||||
// }
|
||||
|
||||
// #endregion
|
||||
|
||||
//}
|
||||
|
||||
//#endregion Designer generated code
|
@ -1,115 +0,0 @@
|
||||
using System;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace HaoYueNet.ServerNetworkNet4x
|
||||
{
|
||||
public static class BaseData
|
||||
{
|
||||
/// <summary>
|
||||
/// 心跳包数据
|
||||
/// </summary>
|
||||
public static byte[] HeartbeatData = new byte[5] { 0x05, 0x00, 0x00, 0x00, 0x00 };
|
||||
|
||||
public static void writeInt(byte[] buf, int offset, int value)
|
||||
{
|
||||
buf[offset++] = (byte)(255 & value);
|
||||
buf[offset++] = (byte)(255 & value >> 8);
|
||||
buf[offset++] = (byte)(255 & value >> 16);
|
||||
//buf[offset++] = (byte)(255 & value >>> 24);
|
||||
buf[offset++] = (byte)(255 & value >> 24);
|
||||
}
|
||||
|
||||
public static void writeUInt16(byte[] buf, int offset, int value)
|
||||
{
|
||||
buf[offset++] = (byte)(255 & value);
|
||||
buf[offset++] = (byte)(255 & value >> 8);
|
||||
}
|
||||
|
||||
public static class HunterNet_Heartbeat
|
||||
{
|
||||
public static void SetDataToSocketAsyncEventArgs(SocketAsyncEventArgs myreadEventArgs)
|
||||
{
|
||||
myreadEventArgs.SetBuffer(HeartbeatData, 0, HeartbeatData.Length);
|
||||
}
|
||||
}
|
||||
|
||||
public static class HunterNet_S2C
|
||||
{
|
||||
public static void SetDataToSocketAsyncEventArgs(SocketAsyncEventArgs myreadEventArgs, UInt16 CmdID, UInt16 Error, byte[] AddonBytes_Data)
|
||||
{
|
||||
byte[] data = CreatePkgData(CmdID, Error, AddonBytes_Data);
|
||||
myreadEventArgs.SetBuffer(data, 0, data.Length);
|
||||
}
|
||||
|
||||
public static byte[] CreatePkgData(UInt16 CmdID, UInt16 Error, byte[] AddonBytes_Data)
|
||||
{
|
||||
//用Buffer.BlockCopy拷贝
|
||||
//包长度
|
||||
int AllLenght = 4 + 2 + 2 + AddonBytes_Data.Length;
|
||||
byte[] BufferData = new byte[AllLenght];
|
||||
|
||||
//包长度
|
||||
writeInt(BufferData, 0, AllLenght);
|
||||
|
||||
//CMDID
|
||||
writeUInt16(BufferData, 4, CmdID);
|
||||
|
||||
//Error
|
||||
writeUInt16(BufferData, 4 + 2, CmdID);
|
||||
|
||||
//DATA
|
||||
Buffer.BlockCopy(AddonBytes_Data, 0, BufferData, 4 + 2 + 2, AddonBytes_Data.Length);
|
||||
|
||||
return BufferData;
|
||||
}
|
||||
|
||||
public static void AnalysisPkgData(byte[] srcdata, out UInt16 CmdID, out UInt16 Error, out byte[] data)
|
||||
{
|
||||
CmdID = BitConverter.ToUInt16(srcdata, 0);
|
||||
Error = BitConverter.ToUInt16(srcdata, 2);
|
||||
data = new byte[srcdata.Length - 2 - 2];
|
||||
Array.Copy(srcdata, 4, data, 0, data.Length);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public static class HunterNet_C2S
|
||||
{
|
||||
public static void SetDataToSocketAsyncEventArgs(SocketAsyncEventArgs myreadEventArgs, UInt16 CmdID, byte[] AddonBytes_Data)
|
||||
{
|
||||
byte[] data = CreatePkgData(CmdID, AddonBytes_Data);
|
||||
myreadEventArgs.SetBuffer(data, 0, data.Length);
|
||||
}
|
||||
|
||||
public static byte[] CreatePkgData(UInt16 CmdID, byte[] AddonBytes_Data)
|
||||
{
|
||||
byte[] AddonBytes_CmdID = BitConverter.GetBytes(CmdID);
|
||||
int AllLenght = AddonBytes_CmdID.Length + AddonBytes_Data.Length + 4;
|
||||
int LastIndex = 0;
|
||||
//包长度
|
||||
byte[] AddonBytes_Lenght = BitConverter.GetBytes(AllLenght);
|
||||
|
||||
byte[] BufferData = new byte[AllLenght];
|
||||
//包长度
|
||||
Buffer.BlockCopy(AddonBytes_Lenght, 0, BufferData, LastIndex, AddonBytes_Lenght.Length);
|
||||
LastIndex += AddonBytes_Lenght.Length;
|
||||
|
||||
//CMDID
|
||||
Buffer.BlockCopy(AddonBytes_CmdID, 0, BufferData, LastIndex, AddonBytes_CmdID.Length);
|
||||
LastIndex += AddonBytes_CmdID.Length;
|
||||
|
||||
//DATA
|
||||
Buffer.BlockCopy(AddonBytes_Data, 0, BufferData, LastIndex, AddonBytes_Data.Length);
|
||||
LastIndex += AddonBytes_Data.Length;
|
||||
return BufferData;
|
||||
}
|
||||
|
||||
public static void AnalysisPkgData(byte[] srcdata, out UInt16 CmdID, out byte[] data)
|
||||
{
|
||||
data = new byte[srcdata.Length - 2];
|
||||
CmdID = BitConverter.ToUInt16(srcdata, 0);
|
||||
Array.Copy(srcdata, 2, data, 0, data.Length);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -1,61 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProjectGuid>{036F9BD9-308C-4194-AB40-C5952EF0E9F5}</ProjectGuid>
|
||||
<OutputType>Library</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>HaoYueNet.ServerNetworkNet4x</RootNamespace>
|
||||
<AssemblyName>HaoYueNet.ServerNetworkNet4x</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<Deterministic>true</Deterministic>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>bin\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<!--避免 错误 CS8630 无效的 nullable 值: C# 7.3 的“Enable”。请使用语言版本 8.0 或更高版本 -->
|
||||
<LangVersion>8.0</LangVersion>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Xml.Linq" />
|
||||
<Reference Include="System.Data.DataSetExtensions" />
|
||||
<Reference Include="Microsoft.CSharp" />
|
||||
<Reference Include="System.Data" />
|
||||
<Reference Include="System.Net.Http" />
|
||||
<Reference Include="System.Xml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="BaseData.cs" />
|
||||
<Compile Include="NetWork\AsyncUserToken.cs" />
|
||||
<Compile Include="NetWork\BufferManager.cs" />
|
||||
<Compile Include="NetWork\MemoryStreamPool.cs" />
|
||||
<Compile Include="NetWork\SocketEventPool.cs" />
|
||||
<Compile Include="NetWork\SourceMode\TcpSaeaServer_SourceMode.cs" />
|
||||
<Compile Include="NetWork\SourceMode\TokenMsgPool_SourceMode.cs" />
|
||||
<Compile Include="NetWork\TcpSaeaServer.cs" />
|
||||
<Compile Include="NetWork\TokenMsgPool.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<Compile Include="ProtobufHunterNetCore.cs" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
</Project>
|
@ -1,57 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
|
||||
namespace HaoYueNet.ServerNetworkNet4x
|
||||
{
|
||||
public class TokenWithMsg_SourceMode
|
||||
{
|
||||
public AsyncUserToken token;
|
||||
public byte[] data;
|
||||
public bool bHeartbeat;
|
||||
}
|
||||
|
||||
public class TokenMsgPool_SourceMode
|
||||
{
|
||||
//Stack<TokenWithMsg> msg_pool;
|
||||
Queue<TokenWithMsg_SourceMode> msg_pool;
|
||||
|
||||
public TokenMsgPool_SourceMode(int capacity)
|
||||
{
|
||||
msg_pool = new Queue<TokenWithMsg_SourceMode>(capacity);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 向 Queue 的末尾添加一个对象。
|
||||
/// </summary>
|
||||
/// <param name="item"></param>
|
||||
public void Enqueue(TokenWithMsg_SourceMode item)
|
||||
{
|
||||
lock (msg_pool)
|
||||
{
|
||||
msg_pool.Enqueue(item);
|
||||
}
|
||||
}
|
||||
|
||||
//移除并返回在 Queue 的开头的对象。
|
||||
public TokenWithMsg_SourceMode Dequeue()
|
||||
{
|
||||
lock (msg_pool)
|
||||
{
|
||||
return msg_pool.Dequeue();
|
||||
}
|
||||
}
|
||||
|
||||
public int Count
|
||||
{
|
||||
get { return msg_pool.Count; }
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
msg_pool.Clear();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,36 +0,0 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// 有关程序集的一般信息由以下
|
||||
// 控制。更改这些特性值可修改
|
||||
// 与程序集关联的信息。
|
||||
[assembly: AssemblyTitle("HaoYueNet.ServerNetworkNet4xNet4x")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("HaoYueNet.ServerNetworkNet4xNet4x")]
|
||||
[assembly: AssemblyCopyright("Copyright © 2024")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// 将 ComVisible 设置为 false 会使此程序集中的类型
|
||||
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
|
||||
//请将此类型的 ComVisible 特性设置为 true。
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
|
||||
[assembly: Guid("036f9bd9-308c-4194-ab40-c5952ef0e9f5")]
|
||||
|
||||
// 程序集的版本信息由下列四个值组成:
|
||||
//
|
||||
// 主版本
|
||||
// 次版本
|
||||
// 生成号
|
||||
// 修订号
|
||||
//
|
||||
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
|
||||
//通过使用 "*",如下所示:
|
||||
// [assembly: AssemblyVersion("1.0.*")]
|
||||
[assembly: AssemblyVersion("1.0.0.0")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.0")]
|
@ -1,506 +0,0 @@
|
||||
//// <auto-generated>
|
||||
//// Generated by the protocol buffer compiler. DO NOT EDIT!
|
||||
//// source: protobuf_HunterNetCore.proto
|
||||
//// </auto-generated>
|
||||
//#pragma warning disable 1591, 0612, 3021
|
||||
//#region Designer generated code
|
||||
|
||||
//using pb = global::Google.Protobuf;
|
||||
//using pbc = global::Google.Protobuf.Collections;
|
||||
//using pbr = global::Google.Protobuf.Reflection;
|
||||
//using scg = global::System.Collections.Generic;
|
||||
//namespace HunterProtobufCore {
|
||||
|
||||
// /// <summary>Holder for reflection information generated from protobuf_HunterNetCore.proto</summary>
|
||||
// public static partial class ProtobufHunterNetCoreReflection {
|
||||
|
||||
// #region Descriptor
|
||||
// /// <summary>File descriptor for protobuf_HunterNetCore.proto</summary>
|
||||
// public static pbr::FileDescriptor Descriptor {
|
||||
// get { return descriptor; }
|
||||
// }
|
||||
// private static pbr::FileDescriptor descriptor;
|
||||
|
||||
// static ProtobufHunterNetCoreReflection() {
|
||||
// byte[] descriptorData = global::System.Convert.FromBase64String(
|
||||
// string.Concat(
|
||||
// "Chxwcm90b2J1Zl9IdW50ZXJOZXRDb3JlLnByb3RvEhJIdW50ZXJQcm90b2J1",
|
||||
// "ZkNvcmUiSAoNSHVudGVyTmV0X0MyUxIbChNIdW50ZXJOZXRDb3JlX0NtZElE",
|
||||
// "GAEgASgFEhoKEkh1bnRlck5ldENvcmVfRGF0YRgCIAEoDCJpCg1IdW50ZXJO",
|
||||
// "ZXRfUzJDEhsKE0h1bnRlck5ldENvcmVfQ21kSUQYASABKAUSHwoXSHVudGVy",
|
||||
// "TmV0Q29yZV9FUlJPUkNvZGUYAiABKAUSGgoSSHVudGVyTmV0Q29yZV9EYXRh",
|
||||
// "GAMgASgMQgJIAWIGcHJvdG8z"));
|
||||
// descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
|
||||
// new pbr::FileDescriptor[] { },
|
||||
// new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
|
||||
// new pbr::GeneratedClrTypeInfo(typeof(global::HunterProtobufCore.HunterNet_C2S), global::HunterProtobufCore.HunterNet_C2S.Parser, new[]{ "HunterNetCoreCmdID", "HunterNetCoreData" }, null, null, null, null),
|
||||
// new pbr::GeneratedClrTypeInfo(typeof(global::HunterProtobufCore.HunterNet_S2C), global::HunterProtobufCore.HunterNet_S2C.Parser, new[]{ "HunterNetCoreCmdID", "HunterNetCoreERRORCode", "HunterNetCoreData" }, null, null, null, null)
|
||||
// }));
|
||||
// }
|
||||
// #endregion
|
||||
|
||||
// }
|
||||
// #region Messages
|
||||
// /// <summary>
|
||||
// ///上行
|
||||
// /// </summary>
|
||||
// public sealed partial class HunterNet_C2S : pb::IMessage<HunterNet_C2S>
|
||||
// #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
|
||||
// , pb::IBufferMessage
|
||||
// #endif
|
||||
// {
|
||||
// private static readonly pb::MessageParser<HunterNet_C2S> _parser = new pb::MessageParser<HunterNet_C2S>(() => new HunterNet_C2S());
|
||||
// private pb::UnknownFieldSet _unknownFields;
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public static pb::MessageParser<HunterNet_C2S> Parser { get { return _parser; } }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public static pbr::MessageDescriptor Descriptor {
|
||||
// get { return global::HunterProtobufCore.ProtobufHunterNetCoreReflection.Descriptor.MessageTypes[0]; }
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// pbr::MessageDescriptor pb::IMessage.Descriptor {
|
||||
// get { return Descriptor; }
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public HunterNet_C2S() {
|
||||
// OnConstruction();
|
||||
// }
|
||||
|
||||
// partial void OnConstruction();
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public HunterNet_C2S(HunterNet_C2S other) : this() {
|
||||
// hunterNetCoreCmdID_ = other.hunterNetCoreCmdID_;
|
||||
// hunterNetCoreData_ = other.hunterNetCoreData_;
|
||||
// _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public HunterNet_C2S Clone() {
|
||||
// return new HunterNet_C2S(this);
|
||||
// }
|
||||
|
||||
// /// <summary>Field number for the "HunterNetCore_CmdID" field.</summary>
|
||||
// public const int HunterNetCoreCmdIDFieldNumber = 1;
|
||||
// private int hunterNetCoreCmdID_;
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public int HunterNetCoreCmdID {
|
||||
// get { return hunterNetCoreCmdID_; }
|
||||
// set {
|
||||
// hunterNetCoreCmdID_ = value;
|
||||
// }
|
||||
// }
|
||||
|
||||
// /// <summary>Field number for the "HunterNetCore_Data" field.</summary>
|
||||
// public const int HunterNetCoreDataFieldNumber = 2;
|
||||
// private pb::ByteString hunterNetCoreData_ = pb::ByteString.Empty;
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public pb::ByteString HunterNetCoreData {
|
||||
// get { return hunterNetCoreData_; }
|
||||
// set {
|
||||
// hunterNetCoreData_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
|
||||
// }
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public override bool Equals(object other) {
|
||||
// return Equals(other as HunterNet_C2S);
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public bool Equals(HunterNet_C2S other) {
|
||||
// if (ReferenceEquals(other, null)) {
|
||||
// return false;
|
||||
// }
|
||||
// if (ReferenceEquals(other, this)) {
|
||||
// return true;
|
||||
// }
|
||||
// if (HunterNetCoreCmdID != other.HunterNetCoreCmdID) return false;
|
||||
// if (HunterNetCoreData != other.HunterNetCoreData) return false;
|
||||
// return Equals(_unknownFields, other._unknownFields);
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public override int GetHashCode() {
|
||||
// int hash = 1;
|
||||
// if (HunterNetCoreCmdID != 0) hash ^= HunterNetCoreCmdID.GetHashCode();
|
||||
// if (HunterNetCoreData.Length != 0) hash ^= HunterNetCoreData.GetHashCode();
|
||||
// if (_unknownFields != null) {
|
||||
// hash ^= _unknownFields.GetHashCode();
|
||||
// }
|
||||
// return hash;
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public override string ToString() {
|
||||
// return pb::JsonFormatter.ToDiagnosticString(this);
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public void WriteTo(pb::CodedOutputStream output) {
|
||||
// #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
|
||||
// output.WriteRawMessage(this);
|
||||
// #else
|
||||
// if (HunterNetCoreCmdID != 0) {
|
||||
// output.WriteRawTag(8);
|
||||
// output.WriteInt32(HunterNetCoreCmdID);
|
||||
// }
|
||||
// if (HunterNetCoreData.Length != 0) {
|
||||
// output.WriteRawTag(18);
|
||||
// output.WriteBytes(HunterNetCoreData);
|
||||
// }
|
||||
// if (_unknownFields != null) {
|
||||
// _unknownFields.WriteTo(output);
|
||||
// }
|
||||
// #endif
|
||||
// }
|
||||
|
||||
// #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
|
||||
// if (HunterNetCoreCmdID != 0) {
|
||||
// output.WriteRawTag(8);
|
||||
// output.WriteInt32(HunterNetCoreCmdID);
|
||||
// }
|
||||
// if (HunterNetCoreData.Length != 0) {
|
||||
// output.WriteRawTag(18);
|
||||
// output.WriteBytes(HunterNetCoreData);
|
||||
// }
|
||||
// if (_unknownFields != null) {
|
||||
// _unknownFields.WriteTo(ref output);
|
||||
// }
|
||||
// }
|
||||
// #endif
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public int CalculateSize() {
|
||||
// int size = 0;
|
||||
// if (HunterNetCoreCmdID != 0) {
|
||||
// size += 1 + pb::CodedOutputStream.ComputeInt32Size(HunterNetCoreCmdID);
|
||||
// }
|
||||
// if (HunterNetCoreData.Length != 0) {
|
||||
// size += 1 + pb::CodedOutputStream.ComputeBytesSize(HunterNetCoreData);
|
||||
// }
|
||||
// if (_unknownFields != null) {
|
||||
// size += _unknownFields.CalculateSize();
|
||||
// }
|
||||
// return size;
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public void MergeFrom(HunterNet_C2S other) {
|
||||
// if (other == null) {
|
||||
// return;
|
||||
// }
|
||||
// if (other.HunterNetCoreCmdID != 0) {
|
||||
// HunterNetCoreCmdID = other.HunterNetCoreCmdID;
|
||||
// }
|
||||
// if (other.HunterNetCoreData.Length != 0) {
|
||||
// HunterNetCoreData = other.HunterNetCoreData;
|
||||
// }
|
||||
// _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public void MergeFrom(pb::CodedInputStream input) {
|
||||
// #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
|
||||
// input.ReadRawMessage(this);
|
||||
// #else
|
||||
// uint tag;
|
||||
// while ((tag = input.ReadTag()) != 0) {
|
||||
// switch(tag) {
|
||||
// default:
|
||||
// _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
|
||||
// break;
|
||||
// case 8: {
|
||||
// HunterNetCoreCmdID = input.ReadInt32();
|
||||
// break;
|
||||
// }
|
||||
// case 18: {
|
||||
// HunterNetCoreData = input.ReadBytes();
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// #endif
|
||||
// }
|
||||
|
||||
// #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
|
||||
// uint tag;
|
||||
// while ((tag = input.ReadTag()) != 0) {
|
||||
// switch(tag) {
|
||||
// default:
|
||||
// _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
|
||||
// break;
|
||||
// case 8: {
|
||||
// HunterNetCoreCmdID = input.ReadInt32();
|
||||
// break;
|
||||
// }
|
||||
// case 18: {
|
||||
// HunterNetCoreData = input.ReadBytes();
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// #endif
|
||||
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// ///下行
|
||||
// /// </summary>
|
||||
// public sealed partial class HunterNet_S2C : pb::IMessage<HunterNet_S2C>
|
||||
// #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
|
||||
// , pb::IBufferMessage
|
||||
// #endif
|
||||
// {
|
||||
// private static readonly pb::MessageParser<HunterNet_S2C> _parser = new pb::MessageParser<HunterNet_S2C>(() => new HunterNet_S2C());
|
||||
// private pb::UnknownFieldSet _unknownFields;
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public static pb::MessageParser<HunterNet_S2C> Parser { get { return _parser; } }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public static pbr::MessageDescriptor Descriptor {
|
||||
// get { return global::HunterProtobufCore.ProtobufHunterNetCoreReflection.Descriptor.MessageTypes[1]; }
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// pbr::MessageDescriptor pb::IMessage.Descriptor {
|
||||
// get { return Descriptor; }
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public HunterNet_S2C() {
|
||||
// OnConstruction();
|
||||
// }
|
||||
|
||||
// partial void OnConstruction();
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public HunterNet_S2C(HunterNet_S2C other) : this() {
|
||||
// hunterNetCoreCmdID_ = other.hunterNetCoreCmdID_;
|
||||
// hunterNetCoreERRORCode_ = other.hunterNetCoreERRORCode_;
|
||||
// hunterNetCoreData_ = other.hunterNetCoreData_;
|
||||
// _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public HunterNet_S2C Clone() {
|
||||
// return new HunterNet_S2C(this);
|
||||
// }
|
||||
|
||||
// /// <summary>Field number for the "HunterNetCore_CmdID" field.</summary>
|
||||
// public const int HunterNetCoreCmdIDFieldNumber = 1;
|
||||
// private int hunterNetCoreCmdID_;
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public int HunterNetCoreCmdID {
|
||||
// get { return hunterNetCoreCmdID_; }
|
||||
// set {
|
||||
// hunterNetCoreCmdID_ = value;
|
||||
// }
|
||||
// }
|
||||
|
||||
// /// <summary>Field number for the "HunterNetCore_ERRORCode" field.</summary>
|
||||
// public const int HunterNetCoreERRORCodeFieldNumber = 2;
|
||||
// private int hunterNetCoreERRORCode_;
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public int HunterNetCoreERRORCode {
|
||||
// get { return hunterNetCoreERRORCode_; }
|
||||
// set {
|
||||
// hunterNetCoreERRORCode_ = value;
|
||||
// }
|
||||
// }
|
||||
|
||||
// /// <summary>Field number for the "HunterNetCore_Data" field.</summary>
|
||||
// public const int HunterNetCoreDataFieldNumber = 3;
|
||||
// private pb::ByteString hunterNetCoreData_ = pb::ByteString.Empty;
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public pb::ByteString HunterNetCoreData {
|
||||
// get { return hunterNetCoreData_; }
|
||||
// set {
|
||||
// hunterNetCoreData_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
|
||||
// }
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public override bool Equals(object other) {
|
||||
// return Equals(other as HunterNet_S2C);
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public bool Equals(HunterNet_S2C other) {
|
||||
// if (ReferenceEquals(other, null)) {
|
||||
// return false;
|
||||
// }
|
||||
// if (ReferenceEquals(other, this)) {
|
||||
// return true;
|
||||
// }
|
||||
// if (HunterNetCoreCmdID != other.HunterNetCoreCmdID) return false;
|
||||
// if (HunterNetCoreERRORCode != other.HunterNetCoreERRORCode) return false;
|
||||
// if (HunterNetCoreData != other.HunterNetCoreData) return false;
|
||||
// return Equals(_unknownFields, other._unknownFields);
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public override int GetHashCode() {
|
||||
// int hash = 1;
|
||||
// if (HunterNetCoreCmdID != 0) hash ^= HunterNetCoreCmdID.GetHashCode();
|
||||
// if (HunterNetCoreERRORCode != 0) hash ^= HunterNetCoreERRORCode.GetHashCode();
|
||||
// if (HunterNetCoreData.Length != 0) hash ^= HunterNetCoreData.GetHashCode();
|
||||
// if (_unknownFields != null) {
|
||||
// hash ^= _unknownFields.GetHashCode();
|
||||
// }
|
||||
// return hash;
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public override string ToString() {
|
||||
// return pb::JsonFormatter.ToDiagnosticString(this);
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public void WriteTo(pb::CodedOutputStream output) {
|
||||
// #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
|
||||
// output.WriteRawMessage(this);
|
||||
// #else
|
||||
// if (HunterNetCoreCmdID != 0) {
|
||||
// output.WriteRawTag(8);
|
||||
// output.WriteInt32(HunterNetCoreCmdID);
|
||||
// }
|
||||
// if (HunterNetCoreERRORCode != 0) {
|
||||
// output.WriteRawTag(16);
|
||||
// output.WriteInt32(HunterNetCoreERRORCode);
|
||||
// }
|
||||
// if (HunterNetCoreData.Length != 0) {
|
||||
// output.WriteRawTag(26);
|
||||
// output.WriteBytes(HunterNetCoreData);
|
||||
// }
|
||||
// if (_unknownFields != null) {
|
||||
// _unknownFields.WriteTo(output);
|
||||
// }
|
||||
// #endif
|
||||
// }
|
||||
|
||||
// #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
|
||||
// if (HunterNetCoreCmdID != 0) {
|
||||
// output.WriteRawTag(8);
|
||||
// output.WriteInt32(HunterNetCoreCmdID);
|
||||
// }
|
||||
// if (HunterNetCoreERRORCode != 0) {
|
||||
// output.WriteRawTag(16);
|
||||
// output.WriteInt32(HunterNetCoreERRORCode);
|
||||
// }
|
||||
// if (HunterNetCoreData.Length != 0) {
|
||||
// output.WriteRawTag(26);
|
||||
// output.WriteBytes(HunterNetCoreData);
|
||||
// }
|
||||
// if (_unknownFields != null) {
|
||||
// _unknownFields.WriteTo(ref output);
|
||||
// }
|
||||
// }
|
||||
// #endif
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public int CalculateSize() {
|
||||
// int size = 0;
|
||||
// if (HunterNetCoreCmdID != 0) {
|
||||
// size += 1 + pb::CodedOutputStream.ComputeInt32Size(HunterNetCoreCmdID);
|
||||
// }
|
||||
// if (HunterNetCoreERRORCode != 0) {
|
||||
// size += 1 + pb::CodedOutputStream.ComputeInt32Size(HunterNetCoreERRORCode);
|
||||
// }
|
||||
// if (HunterNetCoreData.Length != 0) {
|
||||
// size += 1 + pb::CodedOutputStream.ComputeBytesSize(HunterNetCoreData);
|
||||
// }
|
||||
// if (_unknownFields != null) {
|
||||
// size += _unknownFields.CalculateSize();
|
||||
// }
|
||||
// return size;
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public void MergeFrom(HunterNet_S2C other) {
|
||||
// if (other == null) {
|
||||
// return;
|
||||
// }
|
||||
// if (other.HunterNetCoreCmdID != 0) {
|
||||
// HunterNetCoreCmdID = other.HunterNetCoreCmdID;
|
||||
// }
|
||||
// if (other.HunterNetCoreERRORCode != 0) {
|
||||
// HunterNetCoreERRORCode = other.HunterNetCoreERRORCode;
|
||||
// }
|
||||
// if (other.HunterNetCoreData.Length != 0) {
|
||||
// HunterNetCoreData = other.HunterNetCoreData;
|
||||
// }
|
||||
// _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public void MergeFrom(pb::CodedInputStream input) {
|
||||
// #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
|
||||
// input.ReadRawMessage(this);
|
||||
// #else
|
||||
// uint tag;
|
||||
// while ((tag = input.ReadTag()) != 0) {
|
||||
// switch(tag) {
|
||||
// default:
|
||||
// _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
|
||||
// break;
|
||||
// case 8: {
|
||||
// HunterNetCoreCmdID = input.ReadInt32();
|
||||
// break;
|
||||
// }
|
||||
// case 16: {
|
||||
// HunterNetCoreERRORCode = input.ReadInt32();
|
||||
// break;
|
||||
// }
|
||||
// case 26: {
|
||||
// HunterNetCoreData = input.ReadBytes();
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// #endif
|
||||
// }
|
||||
|
||||
// #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
|
||||
// uint tag;
|
||||
// while ((tag = input.ReadTag()) != 0) {
|
||||
// switch(tag) {
|
||||
// default:
|
||||
// _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
|
||||
// break;
|
||||
// case 8: {
|
||||
// HunterNetCoreCmdID = input.ReadInt32();
|
||||
// break;
|
||||
// }
|
||||
// case 16: {
|
||||
// HunterNetCoreERRORCode = input.ReadInt32();
|
||||
// break;
|
||||
// }
|
||||
// case 26: {
|
||||
// HunterNetCoreData = input.ReadBytes();
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// #endif
|
||||
|
||||
// }
|
||||
|
||||
// #endregion
|
||||
|
||||
//}
|
||||
|
||||
//#endregion Designer generated code
|
@ -1,7 +1,6 @@
|
||||
using System;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace HaoYueNet.ClientNetworkNet.Standard2
|
||||
namespace HaoYueNet.ClientNetwork
|
||||
{
|
||||
public static class BaseData
|
||||
{
|
||||
@ -9,22 +8,6 @@ namespace HaoYueNet.ClientNetworkNet.Standard2
|
||||
/// 心跳包数据
|
||||
/// </summary>
|
||||
public static byte[] HeartbeatData = new byte[5] { 0x05, 0x00, 0x00, 0x00, 0x00 };
|
||||
|
||||
public static void writeInt(byte[] buf, int offset, int value)
|
||||
{
|
||||
buf[offset++] = (byte)(255 & value);
|
||||
buf[offset++] = (byte)(255 & value >> 8);
|
||||
buf[offset++] = (byte)(255 & value >> 16);
|
||||
//buf[offset++] = (byte)(255 & value >>> 24);
|
||||
buf[offset++] = (byte)(255 & value >> 24);
|
||||
}
|
||||
|
||||
public static void writeUInt16(byte[] buf, int offset, int value)
|
||||
{
|
||||
buf[offset++] = (byte)(255 & value);
|
||||
buf[offset++] = (byte)(255 & value >> 8);
|
||||
}
|
||||
|
||||
public static class HunterNet_Heartbeat
|
||||
{
|
||||
public static void SetDataToSocketAsyncEventArgs(SocketAsyncEventArgs myreadEventArgs)
|
||||
@ -32,99 +15,35 @@ namespace HaoYueNet.ClientNetworkNet.Standard2
|
||||
myreadEventArgs.SetBuffer(HeartbeatData, 0, HeartbeatData.Length);
|
||||
}
|
||||
}
|
||||
|
||||
public static class HunterNet_S2C
|
||||
{
|
||||
public static void SetDataToSocketAsyncEventArgs(SocketAsyncEventArgs myreadEventArgs, UInt16 CmdID, UInt16 Error, byte[] AddonBytes_Data)
|
||||
{
|
||||
byte[] data = CreatePkgData(CmdID, Error, AddonBytes_Data);
|
||||
myreadEventArgs.SetBuffer(data,0, data.Length);
|
||||
myreadEventArgs.SetBuffer(data,0,data.Length);
|
||||
}
|
||||
|
||||
public static byte[] CreatePkgData(UInt16 CmdID, UInt16 Error, byte[] AddonBytes_Data)
|
||||
{
|
||||
//byte[] AddonBytes_CmdID = BitConverter.GetBytes(CmdID);
|
||||
//byte[] AddonBytes_Error = BitConverter.GetBytes(Error);
|
||||
//int AllLenght = AddonBytes_CmdID.Length + AddonBytes_Error.Length + AddonBytes_Data.Length + 4;
|
||||
//int LastIndex = 0;
|
||||
////包长度
|
||||
//byte[] AddonBytes_Lenght = BitConverter.GetBytes(AllLenght);
|
||||
|
||||
//byte[] BufferData = new byte[AllLenght];
|
||||
////包长度
|
||||
//AddonBytes_Lenght.CopyTo(BufferData, LastIndex);
|
||||
//LastIndex += AddonBytes_Lenght.Length;
|
||||
|
||||
////CMDID
|
||||
//AddonBytes_CmdID.CopyTo(BufferData, LastIndex);
|
||||
//LastIndex += AddonBytes_CmdID.Length;
|
||||
|
||||
////Error
|
||||
//AddonBytes_Error.CopyTo(BufferData, LastIndex);
|
||||
//LastIndex += AddonBytes_Error.Length;
|
||||
|
||||
////DATA
|
||||
//AddonBytes_Data.CopyTo(BufferData, LastIndex);
|
||||
//LastIndex += AddonBytes_Data.Length;
|
||||
//return BufferData;
|
||||
|
||||
////用Buffer.BlockCopy拷贝
|
||||
//byte[] AddonBytes_CmdID = BitConverter.GetBytes(CmdID);
|
||||
//byte[] AddonBytes_Error = BitConverter.GetBytes(Error);
|
||||
//int AllLenght = AddonBytes_CmdID.Length + AddonBytes_Error.Length + AddonBytes_Data.Length + 4;
|
||||
//int LastIndex = 0;
|
||||
////包长度
|
||||
//byte[] AddonBytes_Lenght = BitConverter.GetBytes(AllLenght);
|
||||
|
||||
//byte[] BufferData = new byte[AllLenght];
|
||||
////包长度
|
||||
//Buffer.BlockCopy(AddonBytes_Lenght, 0, BufferData, LastIndex, AddonBytes_Lenght.Length);
|
||||
//LastIndex += AddonBytes_Lenght.Length;
|
||||
|
||||
////CMDID
|
||||
//Buffer.BlockCopy(AddonBytes_CmdID, 0, BufferData, LastIndex, AddonBytes_CmdID.Length);
|
||||
//LastIndex += AddonBytes_CmdID.Length;
|
||||
|
||||
////Error
|
||||
//Buffer.BlockCopy(AddonBytes_Error, 0, BufferData, LastIndex, AddonBytes_Error.Length);
|
||||
//LastIndex += AddonBytes_Error.Length;
|
||||
|
||||
////DATA
|
||||
//Buffer.BlockCopy(AddonBytes_Data, 0, BufferData, LastIndex, AddonBytes_Data.Length);
|
||||
//LastIndex += AddonBytes_Data.Length;
|
||||
|
||||
|
||||
|
||||
//用Buffer.BlockCopy拷贝
|
||||
//包长度
|
||||
int AllLenght = 4 + 2 + 2 + AddonBytes_Data.Length;
|
||||
byte[] BufferData = new byte[AllLenght];
|
||||
|
||||
//包长度
|
||||
writeInt(BufferData, 0, AllLenght);
|
||||
|
||||
Buffer.BlockCopy(BitConverter.GetBytes(AllLenght), 0, BufferData, 0, sizeof(int));
|
||||
//CMDID
|
||||
writeUInt16(BufferData, 4, CmdID);
|
||||
|
||||
//Error
|
||||
writeUInt16(BufferData, 4 + 2, CmdID);
|
||||
|
||||
Buffer.BlockCopy(BitConverter.GetBytes(CmdID), 0, BufferData, 4, sizeof(UInt16));
|
||||
//ErrID
|
||||
Buffer.BlockCopy(BitConverter.GetBytes(Error), 0, BufferData, 4 + 2, sizeof(UInt16));
|
||||
//DATA
|
||||
Buffer.BlockCopy(AddonBytes_Data, 0, BufferData, 4 + 2 + 2, AddonBytes_Data.Length);
|
||||
|
||||
return BufferData;
|
||||
}
|
||||
|
||||
public static void AnalysisPkgData(byte[] srcdata, out UInt16 CmdID, out UInt16 Error, out byte[] data)
|
||||
public static void AnalysisPkgData(Span<byte> srcdata, out UInt16 CmdID, out UInt16 Error, out byte[] data)
|
||||
{
|
||||
CmdID = BitConverter.ToUInt16(srcdata, 0);
|
||||
Error = BitConverter.ToUInt16(srcdata, 2);
|
||||
data = new byte[srcdata.Length - 2 - 2];
|
||||
Array.Copy(srcdata, 4, data, 0, data.Length);
|
||||
|
||||
CmdID = BitConverter.ToUInt16(srcdata.Slice(0, 2).ToArray(), 0);
|
||||
Error = BitConverter.ToUInt16(srcdata.Slice(2, 2).ToArray(), 0);
|
||||
data = srcdata.Slice(2 + 2).ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
public static class HunterNet_C2S
|
||||
{
|
||||
public static void SetDataToSocketAsyncEventArgs(SocketAsyncEventArgs myreadEventArgs, UInt16 CmdID, byte[] AddonBytes_Data)
|
||||
@ -132,35 +51,26 @@ namespace HaoYueNet.ClientNetworkNet.Standard2
|
||||
byte[] data = CreatePkgData(CmdID, AddonBytes_Data);
|
||||
myreadEventArgs.SetBuffer(data, 0, data.Length);
|
||||
}
|
||||
|
||||
public static byte[] CreatePkgData(UInt16 CmdID, byte[] AddonBytes_Data)
|
||||
{
|
||||
byte[] AddonBytes_CmdID = BitConverter.GetBytes(CmdID);
|
||||
int AllLenght = AddonBytes_CmdID.Length + AddonBytes_Data.Length + 4;
|
||||
int LastIndex = 0;
|
||||
//包长度
|
||||
byte[] AddonBytes_Lenght = BitConverter.GetBytes(AllLenght);
|
||||
|
||||
byte[] BufferData = new byte[AllLenght];
|
||||
//包长度
|
||||
Buffer.BlockCopy(AddonBytes_Lenght, 0, BufferData, LastIndex, AddonBytes_Lenght.Length);
|
||||
LastIndex += AddonBytes_Lenght.Length;
|
||||
|
||||
Buffer.BlockCopy(AddonBytes_Lenght, 0, BufferData, 0, AddonBytes_Lenght.Length);
|
||||
//CMDID
|
||||
Buffer.BlockCopy(AddonBytes_CmdID, 0, BufferData, LastIndex, AddonBytes_CmdID.Length);
|
||||
LastIndex += AddonBytes_CmdID.Length;
|
||||
|
||||
Buffer.BlockCopy(AddonBytes_CmdID, 0, BufferData, 4, AddonBytes_CmdID.Length);
|
||||
//DATA
|
||||
Buffer.BlockCopy(AddonBytes_Data, 0, BufferData, LastIndex, AddonBytes_Data.Length);
|
||||
LastIndex += AddonBytes_Data.Length;
|
||||
Buffer.BlockCopy(AddonBytes_Data, 0, BufferData, 4 + 2, AddonBytes_Data.Length);
|
||||
return BufferData;
|
||||
}
|
||||
|
||||
public static void AnalysisPkgData(byte[] srcdata, out UInt16 CmdID, out byte[] data)
|
||||
public static void AnalysisPkgData(Span<byte> srcdata, out UInt16 CmdID, out byte[] data)
|
||||
{
|
||||
data = new byte[srcdata.Length - 2];
|
||||
CmdID = BitConverter.ToUInt16(srcdata, 0);
|
||||
Array.Copy(srcdata, 2, data, 0, data.Length);
|
||||
CmdID = BitConverter.ToUInt16(srcdata.Slice(0, 2).ToArray(),0);
|
||||
data = srcdata.Slice(2).ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -3,7 +3,7 @@ using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace HaoYueNet.ServerNetworkNet4x
|
||||
namespace HaoYueNet.ClientNetwork.IOCPMode
|
||||
{
|
||||
public class AsyncUserToken
|
||||
{
|
||||
@ -42,7 +42,7 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
public AsyncUserToken()
|
||||
{
|
||||
//this.Buffer = new List<byte>();
|
||||
this.memoryStream = new MemoryStream();
|
||||
memoryStream = new MemoryStream();
|
||||
}
|
||||
/// <summary>
|
||||
/// 响应倒计时计数
|
@ -1,7 +1,7 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace HaoYueNet.ServerNetworkNet4x
|
||||
namespace HaoYueNet.ClientNetwork.IOCPMode
|
||||
{
|
||||
public class BufferManager
|
||||
{
|
||||
@ -40,7 +40,7 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
}
|
||||
else
|
||||
{
|
||||
if ((m_numBytes - m_bufferSize) < m_currentIndex)
|
||||
if (m_numBytes - m_bufferSize < m_currentIndex)
|
||||
{
|
||||
return false;
|
||||
}
|
@ -0,0 +1,43 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
namespace HaoYueNet.ClientNetwork.IOCPMode
|
||||
{
|
||||
|
||||
public class MemoryStreamPools
|
||||
{
|
||||
Stack<MemoryStream> m_pool;
|
||||
|
||||
public MemoryStreamPools(int capacity)
|
||||
{
|
||||
m_pool = new Stack<MemoryStream>(capacity);
|
||||
}
|
||||
|
||||
public void Push(MemoryStream item)
|
||||
{
|
||||
if (item == null) { throw new ArgumentNullException("Items added to a MemoryStream cannot be null"); }
|
||||
lock (m_pool)
|
||||
{
|
||||
m_pool.Push(item);
|
||||
}
|
||||
}
|
||||
public MemoryStream Pop()
|
||||
{
|
||||
lock (m_pool)
|
||||
{
|
||||
return m_pool.Pop();
|
||||
}
|
||||
}
|
||||
|
||||
public int Count
|
||||
{
|
||||
get { return m_pool.Count; }
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
m_pool.Clear();
|
||||
}
|
||||
}
|
||||
}
|
@ -2,7 +2,7 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace HaoYueNet.ServerNetworkNet4x
|
||||
namespace HaoYueNet.ClientNetwork.IOCPMode
|
||||
{
|
||||
|
||||
public class SocketEventPool
|
@ -1,15 +1,16 @@
|
||||
//using HunterProtobufCore;
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
using static HaoYueNet.ServerNetworkNet4x.BaseData;
|
||||
using static HaoYueNet.ClientNetwork.BaseData;
|
||||
|
||||
namespace HaoYueNet.ServerNetworkNet4x
|
||||
namespace HaoYueNet.ClientNetwork.IOCPMode
|
||||
{
|
||||
public class TcpSaeaServer
|
||||
public class TcpSaeaClient
|
||||
{
|
||||
#region 定义属性
|
||||
protected int MaxRevIndexNum = 50;//响应倒计时计数最大值
|
||||
@ -20,7 +21,6 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
public int m_revBufferSize; //最大接收字节数
|
||||
protected BufferManager m_bufferManager;
|
||||
protected const int opsToAlloc = 2;
|
||||
Socket listenSocket; //监听Socket
|
||||
protected SocketEventPool m_Receivepool;
|
||||
protected SocketEventPool m_Sendpool;
|
||||
protected TokenMsgPool msg_pool;
|
||||
@ -43,7 +43,7 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
/// </summary>
|
||||
/// <param name="token">客户端</param>
|
||||
/// <param name="buff">客户端数据</param>
|
||||
public delegate void OnReceiveDataHandler(AsyncUserToken sk, int CMDID, byte[] data);
|
||||
public delegate void OnReceiveDataHandler(AsyncUserToken sk, int CMDID, int ErrID, byte[] data);
|
||||
/// <summary>
|
||||
/// 断开连接
|
||||
/// </summary>
|
||||
@ -80,7 +80,7 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
/// </summary>
|
||||
/// <param name="numConnections">最大连接数</param>
|
||||
/// <param name="receiveBufferSize">缓存区大小</param>
|
||||
public TcpSaeaServer(int numConnections, int receiveBufferSize)
|
||||
public TcpSaeaClient(int numConnections, int receiveBufferSize)
|
||||
{
|
||||
m_clientCount = 0;
|
||||
m_maxConnectNum = numConnections;
|
||||
@ -140,25 +140,11 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
/// <param name="localEndPoint"></param>
|
||||
/// <param name="bReuseAddress">是否端口重用</param>
|
||||
/// <returns></returns>
|
||||
public bool Start(IPEndPoint localEndPoint, bool bReuseAddress = false)
|
||||
public bool Start()
|
||||
{
|
||||
try
|
||||
{
|
||||
ClearUserToken();
|
||||
listenSocket = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
|
||||
|
||||
if (bReuseAddress)
|
||||
{
|
||||
listenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
OutNetLog("监听:" + listenSocket.LocalEndPoint.ToString());
|
||||
|
||||
_heartTimer = new System.Timers.Timer();
|
||||
_heartTimer.Interval = TimerInterval;
|
||||
@ -174,6 +160,7 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 停止服务
|
||||
/// </summary>
|
||||
@ -189,11 +176,20 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
}
|
||||
try
|
||||
{
|
||||
listenSocket.Shutdown(SocketShutdown.Both);
|
||||
for (int i = 0; i < m_clients.Count; i++)
|
||||
{
|
||||
m_clients[i].Socket.Shutdown(SocketShutdown.Both);
|
||||
}
|
||||
//listenSocket.Shutdown(SocketShutdown.Both);
|
||||
|
||||
for (int i = 0; i < m_clients.Count; i++)
|
||||
{
|
||||
m_clients[i].Socket.Close();
|
||||
}
|
||||
}
|
||||
catch (Exception) { }
|
||||
|
||||
listenSocket.Close();
|
||||
//listenSocket.Close();
|
||||
int c_count = m_clients.Count;
|
||||
ClearUserToken();
|
||||
|
||||
@ -202,7 +198,7 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
}
|
||||
public void CloseClient(AsyncUserToken token)
|
||||
{
|
||||
try {token.Socket.Shutdown(SocketShutdown.Both);}
|
||||
try { token.Socket.Shutdown(SocketShutdown.Both); }
|
||||
catch (Exception) { }
|
||||
}
|
||||
/// <summary>
|
||||
@ -234,7 +230,11 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
#region Token管理
|
||||
public AsyncUserToken GetAsyncUserTokenForSocket(Socket sk)
|
||||
{
|
||||
return _DictSocketAsyncUserToken.ContainsKey(sk) ? _DictSocketAsyncUserToken[sk] : null;
|
||||
AsyncUserToken result;
|
||||
if (_DictSocketAsyncUserToken.TryGetValue(sk, out result))
|
||||
return result;
|
||||
return null;
|
||||
//return _DictSocketAsyncUserToken.ContainsKey(sk) ? _DictSocketAsyncUserToken[sk] : null;
|
||||
}
|
||||
void AddUserToken(AsyncUserToken userToken)
|
||||
{
|
||||
@ -287,47 +287,42 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 监听IOCP循环
|
||||
/// <summary>
|
||||
/// 开始接受客户端的连接请求的操作
|
||||
/// </summary>
|
||||
/// <param name="acceptEventArg">在服务器的侦听套接字上发出接受操作时要使用的上下文对象</param>
|
||||
public void StartAccept(SocketAsyncEventArgs acceptEventArg)
|
||||
|
||||
|
||||
#region 连接
|
||||
public void StartConnect(string ip, int port, Socket socket, SocketAsyncEventArgs connectEventArg = null)
|
||||
{
|
||||
if (acceptEventArg == null)
|
||||
if (connectEventArg == null)
|
||||
{
|
||||
acceptEventArg = new SocketAsyncEventArgs();
|
||||
acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(AcceptEventArg_Completed);
|
||||
connectEventArg = new SocketAsyncEventArgs();
|
||||
connectEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed);
|
||||
}
|
||||
else
|
||||
{
|
||||
// socket must be cleared since the context object is being reused
|
||||
acceptEventArg.AcceptSocket = null;
|
||||
connectEventArg.AcceptSocket = null;
|
||||
//TODO ??
|
||||
//这里其实AcceptSocket是服务端用的,非监听的客户端用,本来就为空,清不清理没什么卵用,但是connectEventArg.ConnectSocket是只读的的
|
||||
}
|
||||
|
||||
connectEventArg.RemoteEndPoint = new DnsEndPoint(ip, port);
|
||||
|
||||
m_maxNumberAcceptedClients.WaitOne();
|
||||
if (!listenSocket.AcceptAsync(acceptEventArg))
|
||||
|
||||
if (!socket.ConnectAsync(connectEventArg))
|
||||
{
|
||||
ProcessAccept(acceptEventArg);
|
||||
ProcessConnect(connectEventArg);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 此方法是与Socket关联的回调方法。AcceptAsync操作,并在接受操作完成时调用
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
void AcceptEventArg_Completed(object sender, SocketAsyncEventArgs e)
|
||||
{
|
||||
ProcessAccept(e);
|
||||
}
|
||||
private void ProcessAccept(SocketAsyncEventArgs e)
|
||||
|
||||
private void ProcessConnect(SocketAsyncEventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
Interlocked.Increment(ref m_clientCount);
|
||||
|
||||
//确保监听结束时,有连接才抛给数据接收
|
||||
if (e.AcceptSocket.RemoteEndPoint != null)
|
||||
if (e.ConnectSocket.RemoteEndPoint != null)
|
||||
{
|
||||
// Get the socket for the accepted client connection and put it into the
|
||||
//ReadEventArg object user token
|
||||
@ -338,11 +333,10 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
readEventArgs.UserToken = new AsyncUserToken();
|
||||
|
||||
userToken = (AsyncUserToken)readEventArgs.UserToken;
|
||||
userToken.Socket = e.AcceptSocket;
|
||||
userToken.Socket = e.ConnectSocket;
|
||||
userToken.ConnectTime = DateTime.Now;
|
||||
userToken.Remote = e.AcceptSocket.RemoteEndPoint;
|
||||
userToken.IPAddress = ((IPEndPoint)(e.AcceptSocket.RemoteEndPoint)).Address;
|
||||
|
||||
userToken.Remote = e.ConnectSocket.RemoteEndPoint;
|
||||
userToken.IPAddress = ((IPEndPoint)e.ConnectSocket.RemoteEndPoint).Address;
|
||||
|
||||
userToken.RevIndex = MaxRevIndexNum;
|
||||
userToken.SendIndex = MaxSendIndexNum;
|
||||
@ -350,7 +344,7 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
AddUserToken(userToken);
|
||||
|
||||
OnClientNumberChange?.Invoke(1, userToken);
|
||||
if (!e.AcceptSocket.ReceiveAsync(readEventArgs))
|
||||
if (!e.ConnectSocket.ReceiveAsync(readEventArgs))
|
||||
{
|
||||
ProcessReceive(readEventArgs);
|
||||
}
|
||||
@ -363,7 +357,7 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
|
||||
// Accept the next connection request
|
||||
if (e.SocketError == SocketError.OperationAborted) return;
|
||||
StartAccept(e);
|
||||
//StartAccept(e);
|
||||
}
|
||||
#endregion
|
||||
|
||||
@ -377,86 +371,67 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
{
|
||||
try
|
||||
{
|
||||
// check if the remote host closed the connection
|
||||
AsyncUserToken token = (AsyncUserToken)e.UserToken;
|
||||
if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
|
||||
{
|
||||
//读取数据
|
||||
//byte[] data = new byte[e.BytesTransferred];
|
||||
//Array.Copy(e.Buffer, e.Offset, data, 0, e.BytesTransferred);
|
||||
//lock (token.Buffer)
|
||||
lock(token.memoryStream)
|
||||
lock (token.memoryStream)
|
||||
{
|
||||
//token.Buffer.AddRange(data);
|
||||
token.memoryStream.Write(e.Buffer, e.Offset, e.BytesTransferred);
|
||||
do
|
||||
{
|
||||
//如果包头不完整
|
||||
//if (token.Buffer.Count < 4)
|
||||
if (token.memoryStream.Length < 4)
|
||||
break;
|
||||
|
||||
////判断包的长度
|
||||
//byte[] lenBytes = token.Buffer.GetRange(0, 4).ToArray();
|
||||
//int packageLen = BitConverter.ToInt32(lenBytes, 0) - 4;
|
||||
//if (packageLen > token.Buffer.Count - 4)
|
||||
//{ //长度不够时,退出循环,让程序继续接收
|
||||
// break;
|
||||
//}
|
||||
|
||||
if (token.memoryStream.Length < 4) break;//包头不完整,继续接收
|
||||
long FristBeginPos = token.memoryStream.Position;
|
||||
byte[] lenBytes = new byte[4];
|
||||
|
||||
//从Byte池申请
|
||||
byte[] lenBytes = ArrayPool<byte>.Shared.Rent(4);
|
||||
|
||||
token.memoryStream.Seek(0, SeekOrigin.Begin);
|
||||
token.memoryStream.Read(lenBytes, 0, 4);
|
||||
int packageLen = BitConverter.ToInt32(lenBytes, 0) - 4;
|
||||
|
||||
//归还byte[]
|
||||
ArrayPool<byte>.Shared.Return(lenBytes);
|
||||
|
||||
if (packageLen > token.memoryStream.Length - 4)
|
||||
{
|
||||
token.memoryStream.Seek(FristBeginPos, SeekOrigin.Begin);
|
||||
//长度不够时,退出循环,让程序继续接收
|
||||
break;
|
||||
break;//长度不够时,退出循环,让程序继续接收
|
||||
}
|
||||
|
||||
////包够长时,则提取出来,交给后面的程序去处理
|
||||
//byte[] rev = token.Buffer.GetRange(4, packageLen).ToArray();
|
||||
//申请byte池 一定要记得回收!!
|
||||
byte[] rev_fromArrayPool = ArrayPool<byte>.Shared.Rent(packageLen);
|
||||
|
||||
byte[] rev = new byte[packageLen];
|
||||
token.memoryStream.Seek(4, SeekOrigin.Begin);
|
||||
token.memoryStream.Read(rev, 0, packageLen);
|
||||
|
||||
//从数据池中移除这组数据
|
||||
//lock (token.Buffer)
|
||||
//{
|
||||
// token.Buffer.RemoveRange(0, packageLen + 4);
|
||||
//}
|
||||
|
||||
token.memoryStream.Read(rev_fromArrayPool, 0, packageLen);
|
||||
token.memoryStream.Seek(FristBeginPos, SeekOrigin.Begin);
|
||||
//从数据池中移除这组数据
|
||||
lock (token.memoryStream)
|
||||
{
|
||||
//token.memoryStream.Position = 0;
|
||||
//token.memoryStream.SetLength(0);
|
||||
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);
|
||||
}
|
||||
|
||||
DataCallBackReady(token, rev);
|
||||
//用Span内存切片,因为来自ArrayPool的byte长度,可能大于本身申请的长度
|
||||
Span<byte> rev_span = rev_fromArrayPool;
|
||||
rev_span = rev_span.Slice(0, packageLen);
|
||||
DataCallBackReady(token, rev_span);
|
||||
|
||||
//这里API处理完后,并没有返回结果,当然结果是要返回的,却不是在这里, 这里的代码只管接收.
|
||||
//若要返回结果,可在API处理中调用此类对象的SendMessage方法,统一打包发送.不要被微软的示例给迷惑了.
|
||||
//} while (token.Buffer.Count > 4);
|
||||
//回收(这里依赖DataCallBackReady中,有一次数据拷贝,这个后续还要进一步精进性能优化,否则不能在这里回收,否则影响业务层)
|
||||
ArrayPool<byte>.Shared.Return(rev_fromArrayPool);
|
||||
} while (token.memoryStream.Length > 4);
|
||||
}
|
||||
|
||||
//继续接收. 为什么要这么写,请看Socket.ReceiveAsync方法的说明
|
||||
//如果返回为False则代表此刻已经完成,不必等待完成端口回调,则直接调用ProcessReceive
|
||||
if (!token.Socket.ReceiveAsync(e))
|
||||
{
|
||||
this.ProcessReceive(e);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
//清理数据
|
||||
token.memoryStream.SetLength(0);
|
||||
token.memoryStream.Seek(0, SeekOrigin.Begin);
|
||||
CloseClientSocket(e);
|
||||
}
|
||||
}
|
||||
@ -485,6 +460,9 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
|
||||
switch (e.LastOperation)
|
||||
{
|
||||
case SocketAsyncOperation.Connect:
|
||||
ProcessConnect(e);
|
||||
break;
|
||||
case SocketAsyncOperation.Receive:
|
||||
ProcessReceive(e);
|
||||
break;
|
||||
@ -504,19 +482,12 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
/// </summary>
|
||||
/// <param name="CMDID"></param>
|
||||
/// <param name="data">序列化之后的数据</param>
|
||||
public void SendToSocket(Socket sk, int CMDID, int ERRCODE, byte[] data)
|
||||
public void SendToSocket(Socket sk, int CMDID, byte[] data)
|
||||
{
|
||||
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);*/
|
||||
|
||||
//byte[] _finaldata = HunterNet_S2C.CreatePkgData((ushort)CMDID, (ushort)ERRCODE, data);
|
||||
|
||||
SendWithIndex(token, (ushort)CMDID, (ushort)ERRCODE, data);
|
||||
SendWithIndex(token, (ushort)CMDID, data);
|
||||
}
|
||||
|
||||
void SendForMsgPool()
|
||||
{
|
||||
//if (flag_SendForMsgPool) return;
|
||||
@ -539,7 +510,7 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
}
|
||||
else
|
||||
{
|
||||
SendMessage(msg.token, msg.CMDID, msg.Error, msg.data);
|
||||
SendMessage(msg.token, msg.CMDID, msg.data);
|
||||
}
|
||||
msg = null;
|
||||
}
|
||||
@ -572,7 +543,9 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
{
|
||||
SocketAsyncEventArgs myreadEventArgs = m_Sendpool.Pop();
|
||||
myreadEventArgs.UserToken = token;
|
||||
myreadEventArgs.AcceptSocket = token.Socket;
|
||||
//TODO ????客户端用这里是否应该直接就不设置
|
||||
//myreadEventArgs.AcceptSocket = token.Socket;
|
||||
|
||||
//直接写入SocketAsyncEventArgs的Buff
|
||||
HunterNet_Heartbeat.SetDataToSocketAsyncEventArgs(myreadEventArgs);
|
||||
|
||||
@ -601,12 +574,12 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
/// 发送数据并计数
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
void SendWithIndex(AsyncUserToken token, UInt16 CmdID, UInt16 ERRCODE, byte[] data)
|
||||
void SendWithIndex(AsyncUserToken token, ushort CmdID, byte[] data)
|
||||
{
|
||||
try
|
||||
{
|
||||
//发送数据
|
||||
SendMessage(token, CmdID, ERRCODE, data);
|
||||
SendMessage(token, CmdID, data);
|
||||
token.SendIndex = MaxSendIndexNum;
|
||||
}
|
||||
catch
|
||||
@ -615,7 +588,7 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
}
|
||||
}
|
||||
|
||||
void SendMessage(AsyncUserToken token, UInt16 CmdID, UInt16 Error, byte[] data)
|
||||
void SendMessage(AsyncUserToken token, ushort CmdID, byte[] data)
|
||||
{
|
||||
if (token == null || token.Socket == null || !token.Socket.Connected)
|
||||
return;
|
||||
@ -628,7 +601,7 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
myreadEventArgs.AcceptSocket = token.Socket;
|
||||
//myreadEventArgs.SetBuffer(message, 0, message.Length); //将数据放置进去.
|
||||
//更换为CMDID和Data直接写入SocketAsyncEventArgs的Buff
|
||||
HunterNet_S2C.SetDataToSocketAsyncEventArgs(myreadEventArgs, CmdID, Error, data);
|
||||
HunterNet_C2S.SetDataToSocketAsyncEventArgs(myreadEventArgs, CmdID, data);
|
||||
|
||||
//若不需要等待
|
||||
if (!token.Socket.SendAsync(myreadEventArgs))
|
||||
@ -640,7 +613,7 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
else
|
||||
{
|
||||
//先压入队列,等待m_Sendpool回收
|
||||
msg_pool.Enqueue(new TokenWithMsg() { token = token, CMDID = CmdID, Error = Error, data = data });
|
||||
msg_pool.Enqueue(new TokenWithMsg() { token = token, CMDID = CmdID, data = data });
|
||||
//OutNetLog("!!!!压入消息发送队列MSG_Pool");
|
||||
return;
|
||||
}
|
||||
@ -653,7 +626,7 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
#endregion
|
||||
|
||||
#region 处理前预备
|
||||
private void DataCallBackReady(AsyncUserToken sk, byte[] data)
|
||||
private void DataCallBackReady(AsyncUserToken sk, Span<byte> data)
|
||||
{
|
||||
//增加接收计数
|
||||
sk.RevIndex = MaxRevIndexNum;
|
||||
@ -668,13 +641,8 @@ namespace HaoYueNet.ServerNetworkNet4x
|
||||
try
|
||||
{
|
||||
//将数据包交给后台处理,这里你也可以新开个线程来处理.加快速度.
|
||||
/*
|
||||
HunterNet_C2S _s2c = DeSerizlize<HunterNet_C2S>(data);
|
||||
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);
|
||||
HunterNet_S2C.AnalysisPkgData(data, out ushort CmdID, out ushort Error, out byte[] resultdata);
|
||||
OnReceive?.Invoke(sk, CmdID, Error, resultdata);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
@ -0,0 +1,130 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
|
||||
namespace HaoYueNet.ClientNetwork.IOCPMode
|
||||
{
|
||||
public class TokenWithMsg
|
||||
{
|
||||
public AsyncUserToken token;
|
||||
public ushort CMDID;
|
||||
//public UInt16 Error;
|
||||
public byte[] data;
|
||||
public bool bHeartbeat;
|
||||
}
|
||||
|
||||
public class TokenMsgPool
|
||||
{
|
||||
//Stack<TokenWithMsg> msg_pool;
|
||||
Queue<TokenWithMsg> msg_pool;
|
||||
|
||||
public TokenMsgPool(int capacity)
|
||||
{
|
||||
msg_pool = new Queue<TokenWithMsg>(capacity);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 向 Queue 的末尾添加一个对象。
|
||||
/// </summary>
|
||||
/// <param name="item"></param>
|
||||
public void Enqueue(TokenWithMsg item)
|
||||
{
|
||||
lock (msg_pool)
|
||||
{
|
||||
msg_pool.Enqueue(item);
|
||||
}
|
||||
}
|
||||
|
||||
//移除并返回在 Queue 的开头的对象。
|
||||
public TokenWithMsg Dequeue()
|
||||
{
|
||||
lock (msg_pool)
|
||||
{
|
||||
return msg_pool.Dequeue();
|
||||
}
|
||||
}
|
||||
|
||||
public int Count
|
||||
{
|
||||
get { return msg_pool.Count; }
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
msg_pool.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
public class TokenWithMsg
|
||||
{
|
||||
public AsyncUserToken token;
|
||||
public byte[] message;
|
||||
}
|
||||
|
||||
public class TokenMsgPool
|
||||
{
|
||||
//Stack<TokenWithMsg> msg_pool;
|
||||
Queue<TokenWithMsg> msg_pool;
|
||||
|
||||
public TokenMsgPool(int capacity)
|
||||
{
|
||||
//msg_pool = new Stack<TokenWithMsg>(capacity);
|
||||
msg_pool = new Queue<TokenWithMsg>(capacity);
|
||||
}
|
||||
|
||||
//public void Push(TokenWithMsg item)
|
||||
//{
|
||||
// if (item == null) { throw new ArgumentNullException("Items added to a SocketAsyncEventArgsPool cannot be null"); }
|
||||
// lock (msg_pool)
|
||||
// {
|
||||
// msg_pool.Push(item);
|
||||
// }
|
||||
//}
|
||||
|
||||
/// <summary>
|
||||
/// 向 Queue 的末尾添加一个对象。
|
||||
/// </summary>
|
||||
/// <param name="item"></param>
|
||||
public void Enqueue(TokenWithMsg item)
|
||||
{
|
||||
lock (msg_pool)
|
||||
{
|
||||
msg_pool.Enqueue(item);
|
||||
}
|
||||
}
|
||||
|
||||
//移除并返回在 Queue 的开头的对象。
|
||||
public TokenWithMsg Dequeue()
|
||||
{
|
||||
lock (msg_pool)
|
||||
{
|
||||
return msg_pool.Dequeue();
|
||||
}
|
||||
}
|
||||
|
||||
//// Removes a SocketAsyncEventArgs instance from the pool
|
||||
//// and returns the object removed from the pool
|
||||
//public TokenWithMsg Pop()
|
||||
//{
|
||||
// lock (msg_pool)
|
||||
// {
|
||||
// return msg_pool.Pop();
|
||||
// }
|
||||
//}
|
||||
|
||||
// The number of SocketAsyncEventArgs instances in the pool
|
||||
public int Count
|
||||
{
|
||||
get { return msg_pool.Count; }
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
msg_pool.Clear();
|
||||
}
|
||||
}
|
||||
*/
|
||||
}
|
@ -4,15 +4,14 @@ using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
using static HaoYueNet.ClientNetworkNet.Standard2.BaseData;
|
||||
using static HaoYueNet.ClientNetwork.BaseData;
|
||||
|
||||
namespace HaoYueNet.ClientNetworkNet.Standard2
|
||||
namespace HaoYueNet.ClientNetwork
|
||||
{
|
||||
public class NetworkHelperCore
|
||||
{
|
||||
private Socket client;
|
||||
|
||||
|
||||
////响应倒计时计数最大值
|
||||
//private static int MaxRevIndexNum = 6;
|
||||
|
||||
@ -39,7 +38,7 @@ namespace HaoYueNet.ClientNetworkNet.Standard2
|
||||
public static int LastConnectPort;
|
||||
public bool bDetailedLog = false;
|
||||
|
||||
public bool Init(string IP, int port,bool isHadDetailedLog = true, bool bBindReuseAddress = false,int bBindport = 0)
|
||||
public bool Init(string IP, int port,bool isHadDetailedLog = true, bool bBindReuseAddress = false,int bBindport = 0,AddressFamily addressFamily = AddressFamily.InterNetwork)
|
||||
{
|
||||
LogOut("==>初始化网络核心");
|
||||
|
||||
@ -47,7 +46,7 @@ namespace HaoYueNet.ClientNetworkNet.Standard2
|
||||
RevIndex = MaxRevIndexNum;
|
||||
SendIndex = MaxSendIndexNum;
|
||||
|
||||
client = new Socket(SocketType.Stream, ProtocolType.Tcp);
|
||||
client = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp);
|
||||
if (bBindReuseAddress)
|
||||
{
|
||||
client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
|
||||
@ -160,26 +159,6 @@ namespace HaoYueNet.ClientNetworkNet.Standard2
|
||||
}
|
||||
}
|
||||
|
||||
////拼接头长度
|
||||
//private byte[] SendDataWithHead(byte[] message)
|
||||
//{
|
||||
|
||||
// MemoryStream memoryStream = new MemoryStream();//创建一个内存流
|
||||
|
||||
// byte[] BagHead = BitConverter.GetBytes(message.Length + 4);//往字节数组中写入包头(包头自身的长度和消息体的长度)的长度
|
||||
|
||||
// memoryStream.Write(BagHead, 0, BagHead.Length);//将包头写入内存流
|
||||
|
||||
// memoryStream.Write(message, 0, message.Length);//将消息体写入内存流
|
||||
|
||||
// byte[] HeadAndBody = memoryStream.ToArray();//将内存流中的数据写入字节数组
|
||||
|
||||
// memoryStream.Close();//关闭内存
|
||||
// memoryStream.Dispose();//释放资源
|
||||
|
||||
// return HeadAndBody;
|
||||
//}
|
||||
|
||||
/// <summary>
|
||||
/// 供外部调用 发送消息
|
||||
/// </summary>
|
||||
@ -187,13 +166,6 @@ namespace HaoYueNet.ClientNetworkNet.Standard2
|
||||
/// <param name="data">序列化之后的数据</param>
|
||||
public void SendToServer(int CMDID,byte[] data)
|
||||
{
|
||||
//LogOut("准备数据 CMDID=> "+CMDID);
|
||||
/*
|
||||
HunterNet_C2S _c2sdata = new HunterNet_C2S();
|
||||
_c2sdata.HunterNetCoreCmdID = CMDID;
|
||||
_c2sdata.HunterNetCoreData = ByteString.CopyFrom(data);
|
||||
byte[] _finaldata = Serizlize(_c2sdata);
|
||||
*/
|
||||
byte[] _finaldata = HunterNet_C2S.CreatePkgData((ushort)CMDID, data);
|
||||
SendToSocket(_finaldata);
|
||||
}
|
||||
@ -250,46 +222,45 @@ namespace HaoYueNet.ClientNetworkNet.Standard2
|
||||
return;
|
||||
}
|
||||
|
||||
/*
|
||||
HunterNet_S2C _c2s = DeSerizlize<HunterNet_S2C>(data);
|
||||
|
||||
OnReceiveData(_c2s.HunterNetCoreCmdID, _c2s.HunterNetCoreERRORCode, _c2s.HunterNetCoreData.ToArray());
|
||||
*/
|
||||
|
||||
HunterNet_S2C.AnalysisPkgData(data, out ushort CmdID, out ushort Error, out byte[] resultdata);
|
||||
OnReceiveData(CmdID, Error, resultdata);
|
||||
}
|
||||
|
||||
|
||||
MemoryStream memoryStream = new MemoryStream();//开辟一个内存流
|
||||
MemoryStream reciveMemoryStream = new MemoryStream();//开辟一个反复使用的内存流
|
||||
byte[] reciveBuffer = new byte[1024 * 1024 * 2];//开辟一个反复使用的byte[]
|
||||
private void Recive(object o)
|
||||
{
|
||||
var client = o as Socket;
|
||||
//MemoryStream memoryStream = new MemoryStream();//开辟一个内存流
|
||||
|
||||
while (true)
|
||||
{
|
||||
byte[] buffer = new byte[1024 * 1024 * 2];
|
||||
int effective=0;
|
||||
int effective = 0;
|
||||
try
|
||||
{
|
||||
effective = client.Receive(buffer);
|
||||
if (effective == 0)
|
||||
effective = client.Receive(reciveBuffer);
|
||||
if (effective == 0)//为0表示已经断开连接
|
||||
{
|
||||
continue;
|
||||
//清理数据
|
||||
reciveMemoryStream.SetLength(0);
|
||||
reciveMemoryStream.Seek(0, SeekOrigin.Begin);
|
||||
//远程主机强迫关闭了一个现有的连接
|
||||
OnCloseReady();
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch(Exception ex)
|
||||
{
|
||||
//清理数据
|
||||
reciveMemoryStream.SetLength(0);
|
||||
reciveMemoryStream.Seek(0, SeekOrigin.Begin);
|
||||
|
||||
//远程主机强迫关闭了一个现有的连接
|
||||
OnCloseReady();
|
||||
return;
|
||||
//断开连接
|
||||
}
|
||||
|
||||
|
||||
memoryStream.Write(buffer, 0, effective);//将接受到的数据写入内存流中
|
||||
byte[] getData = memoryStream.ToArray();//将内存流中的消息体写入字节数组
|
||||
reciveMemoryStream.Write(reciveBuffer, 0, effective);//将接受到的数据写入内存流中
|
||||
byte[] getData = reciveMemoryStream.ToArray();//将内存流中的消息体写入字节数组
|
||||
int StartIndex = 0;//设置一个读取数据的起始下标
|
||||
|
||||
while (true)
|
||||
@ -310,44 +281,25 @@ namespace HaoYueNet.ClientNetworkNet.Standard2
|
||||
//↓↓↓↓↓↓↓↓ ↓↓↓
|
||||
if (getData.Length - StartIndex < HeadLength || HeadLength == -1)
|
||||
{
|
||||
/* 一种清空流的方式
|
||||
memoryStream.Close();//关闭内存流
|
||||
memoryStream.Dispose();//释放内存资源
|
||||
memoryStream = new MemoryStream();//创建新的内存流
|
||||
*/
|
||||
|
||||
//流复用的方式 不用重新new申请
|
||||
memoryStream.Position = 0;
|
||||
memoryStream.SetLength(0);
|
||||
reciveMemoryStream.Position = 0;
|
||||
reciveMemoryStream.SetLength(0);
|
||||
|
||||
memoryStream.Write(getData, StartIndex, getData.Length - StartIndex);//从新将接受的消息写入内存流
|
||||
reciveMemoryStream.Write(getData, StartIndex, getData.Length - StartIndex);//从新将接受的消息写入内存流
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
//把头去掉,就可以吃了,蛋白质是牛肉的六倍
|
||||
//DataCallBackReady(getData.Skip(StartIndex+4).Take(HeadLength-4).ToArray());
|
||||
|
||||
int CoreLenght = HeadLength - 4;
|
||||
|
||||
//改为Array.Copy 提升效率
|
||||
//byte[] retData = new byte[CoreLenght];
|
||||
//Array.Copy(getData, StartIndex + 4, retData, 0, CoreLenght);
|
||||
//DataCallBackReady(retData);
|
||||
|
||||
//用Span
|
||||
//Span<byte> getData_span = getData;
|
||||
//getData_span = getData_span.Slice(StartIndex + 4,CoreLenght);
|
||||
byte[] getData_span = new byte[CoreLenght];
|
||||
//DATA
|
||||
Buffer.BlockCopy(getData, StartIndex + 4, getData_span, 0, CoreLenght);
|
||||
DataCallBackReady(getData_span);
|
||||
Span<byte> getData_span = getData;
|
||||
getData_span = getData_span.Slice(StartIndex + 4, CoreLenght);
|
||||
DataCallBackReady(getData_span.ToArray());
|
||||
|
||||
StartIndex += HeadLength;//当读取一条完整的数据后,读取数据的起始下标应为当前接受到的消息体的长度(当前数据的尾部或下一条消息的首部)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@ -376,7 +328,6 @@ namespace HaoYueNet.ClientNetworkNet.Standard2
|
||||
|
||||
public void LogOut(string Msg)
|
||||
{
|
||||
//Console.WriteLine(Msg);
|
||||
OnLogOut?.Invoke(Msg);
|
||||
}
|
||||
|
||||
|
@ -3,9 +3,9 @@ using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
using static HaoYueNet.ClientNetworkNet.Standard2.BaseData;
|
||||
using static HaoYueNet.ClientNetwork.BaseData;
|
||||
|
||||
namespace HaoYueNet.ClientNetworkNet.Standard2
|
||||
namespace HaoYueNet.ClientNetwork
|
||||
{
|
||||
public class NetworkHelperP2PCore
|
||||
{
|
||||
@ -27,22 +27,19 @@ namespace HaoYueNet.ClientNetworkNet.Standard2
|
||||
|
||||
private System.Timers.Timer _heartTimer;
|
||||
|
||||
public void Init(string IP, int port, bool bBindReuseAddress = false,int bBindport = 0)
|
||||
public void Init(bool bBindReuseAddress = false,int bBindport = 0, AddressFamily addressFamily = AddressFamily.InterNetwork)
|
||||
{
|
||||
|
||||
LogOut("==>初始化网络核心");
|
||||
|
||||
RevIndex = MaxRevIndexNum;
|
||||
SendIndex = MaxSendIndexNum;
|
||||
|
||||
client = new Socket(SocketType.Stream, ProtocolType.Tcp);
|
||||
client = new Socket(addressFamily,SocketType.Stream, ProtocolType.Tcp);
|
||||
if (bBindReuseAddress)
|
||||
{
|
||||
client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
|
||||
IPEndPoint ipe = new IPEndPoint(IPAddress.Any, Convert.ToInt32(bBindport));
|
||||
client.Bind(ipe);
|
||||
}
|
||||
Connect(IP, port);
|
||||
}
|
||||
|
||||
public bool Connect(string IP, int port)
|
||||
@ -128,26 +125,6 @@ namespace HaoYueNet.ClientNetworkNet.Standard2
|
||||
client.Send(data);
|
||||
}
|
||||
|
||||
////拼接头长度
|
||||
//private byte[] SendDataWithHead(byte[] message)
|
||||
//{
|
||||
|
||||
// MemoryStream memoryStream = new MemoryStream();//创建一个内存流
|
||||
|
||||
// byte[] BagHead = BitConverter.GetBytes(message.Length + 4);//往字节数组中写入包头(包头自身的长度和消息体的长度)的长度
|
||||
|
||||
// memoryStream.Write(BagHead, 0, BagHead.Length);//将包头写入内存流
|
||||
|
||||
// memoryStream.Write(message, 0, message.Length);//将消息体写入内存流
|
||||
|
||||
// byte[] HeadAndBody = memoryStream.ToArray();//将内存流中的数据写入字节数组
|
||||
|
||||
// memoryStream.Close();//关闭内存
|
||||
// memoryStream.Dispose();//释放资源
|
||||
|
||||
// return HeadAndBody;
|
||||
//}
|
||||
|
||||
/// <summary>
|
||||
/// 供外部调用 发送消息
|
||||
/// </summary>
|
||||
@ -156,13 +133,6 @@ namespace HaoYueNet.ClientNetworkNet.Standard2
|
||||
/// <param name="data"></param>
|
||||
public void SendToSocket(int CMDID, int ERRCODE, byte[] data)
|
||||
{
|
||||
//LogOut("准备数据 CMDID=> "+CMDID);
|
||||
/*HunterNet_S2C _s2sdata = new HunterNet_S2C();
|
||||
_s2sdata.HunterNetCoreCmdID = CMDID;
|
||||
_s2sdata.HunterNetCoreERRORCode = ERRCODE;
|
||||
_s2sdata.HunterNetCoreData = ByteString.CopyFrom(data);
|
||||
byte[] _finaldata = Serizlize(_s2sdata);*/
|
||||
|
||||
byte[] _finaldata = HunterNet_S2C.CreatePkgData((ushort)CMDID, (ushort)ERRCODE, data);
|
||||
SendToSocket(_finaldata);
|
||||
}
|
||||
@ -186,24 +156,6 @@ namespace HaoYueNet.ClientNetworkNet.Standard2
|
||||
/// </summary>
|
||||
public event delegate_str OnLogOut;
|
||||
|
||||
///// <summary>
|
||||
///// 用于调用者回调的虚函数
|
||||
///// </summary>
|
||||
///// <param name="data"></param>
|
||||
//public virtual void DataCallBack(int CMDID,int ERRCODE,byte[] data)
|
||||
//{
|
||||
|
||||
//}
|
||||
|
||||
///// <summary>
|
||||
///// 断开连接
|
||||
///// </summary>
|
||||
///// <param name="sk"></param>
|
||||
//public virtual void OnClose()
|
||||
//{
|
||||
|
||||
//}
|
||||
|
||||
/// <summary>
|
||||
/// 做好处理的连接管理
|
||||
/// </summary>
|
||||
@ -240,49 +192,49 @@ namespace HaoYueNet.ClientNetworkNet.Standard2
|
||||
return;
|
||||
}
|
||||
|
||||
/*
|
||||
HunterNet_S2C _c2s = DeSerizlize<HunterNet_S2C>(data);
|
||||
OnDataCallBack(_c2s.HunterNetCoreCmdID, _c2s.HunterNetCoreERRORCode, _c2s.HunterNetCoreData.ToArray());
|
||||
*/
|
||||
HunterNet_S2C.AnalysisPkgData(data, out ushort CmdID, out ushort Error, out byte[] resultdata);
|
||||
OnDataCallBack(CmdID, Error, resultdata);
|
||||
}
|
||||
|
||||
MemoryStream memoryStream = new MemoryStream();//开辟一个内存流
|
||||
MemoryStream reciveMemoryStream = new MemoryStream();//开辟一个反复使用的内存流
|
||||
byte[] reciveBuffer = new byte[1024 * 1024 * 2];//开辟一个反复使用的byte[]
|
||||
private void Recive(object o)
|
||||
{
|
||||
var client = o as Socket;
|
||||
//MemoryStream memoryStream = new MemoryStream();//开辟一个内存流
|
||||
|
||||
while (true)
|
||||
{
|
||||
byte[] buffer = new byte[1024 * 1024 * 2];
|
||||
int effective=0;
|
||||
int effective = 0;
|
||||
try
|
||||
{
|
||||
effective = client.Receive(buffer);
|
||||
if (effective == 0)
|
||||
effective = client.Receive(reciveBuffer);
|
||||
if (effective == 0)//为0表示已经断开连接
|
||||
{
|
||||
continue;
|
||||
//清理数据
|
||||
reciveMemoryStream.SetLength(0);
|
||||
reciveMemoryStream.Seek(0, SeekOrigin.Begin);
|
||||
//远程主机强迫关闭了一个现有的连接
|
||||
OnCloseReady();
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch(Exception ex)
|
||||
catch (Exception ex)
|
||||
{
|
||||
//清理数据
|
||||
reciveMemoryStream.SetLength(0);
|
||||
reciveMemoryStream.Seek(0, SeekOrigin.Begin);
|
||||
|
||||
//远程主机强迫关闭了一个现有的连接
|
||||
OnCloseReady();
|
||||
return;
|
||||
//断开连接
|
||||
}
|
||||
|
||||
|
||||
memoryStream.Write(buffer, 0, effective);//将接受到的数据写入内存流中
|
||||
byte[] getData = memoryStream.ToArray();//将内存流中的消息体写入字节数组
|
||||
reciveMemoryStream.Write(reciveBuffer, 0, effective);//将接受到的数据写入内存流中
|
||||
byte[] getData = reciveMemoryStream.ToArray();//将内存流中的消息体写入字节数组
|
||||
int StartIndex = 0;//设置一个读取数据的起始下标
|
||||
|
||||
while (true)
|
||||
{
|
||||
|
||||
|
||||
if (effective > 0)//如果接受到的消息不为0(不为空)
|
||||
{
|
||||
int HeadLength = 0;//包头长度(包头+包体)
|
||||
@ -299,27 +251,21 @@ namespace HaoYueNet.ClientNetworkNet.Standard2
|
||||
//↓↓↓↓↓↓↓↓ ↓↓↓
|
||||
if (getData.Length - StartIndex < HeadLength || HeadLength == -1)
|
||||
{
|
||||
/* 一种清空流的方式
|
||||
memoryStream.Close();//关闭内存流
|
||||
memoryStream.Dispose();//释放内存资源
|
||||
memoryStream = new MemoryStream();//创建新的内存流
|
||||
*/
|
||||
|
||||
//流复用的方式 不用重新new申请
|
||||
memoryStream.Position = 0;
|
||||
memoryStream.SetLength(0);
|
||||
reciveMemoryStream.Position = 0;
|
||||
reciveMemoryStream.SetLength(0);
|
||||
|
||||
memoryStream.Write(getData, StartIndex, getData.Length - StartIndex);//从新将接受的消息写入内存流
|
||||
reciveMemoryStream.Write(getData, StartIndex, getData.Length - StartIndex);//从新将接受的消息写入内存流
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
//把头去掉,就可以吃了,蛋白质是牛肉的六倍
|
||||
int CoreLenght = HeadLength - 4;
|
||||
byte[] getData_span = new byte[CoreLenght];
|
||||
//DATA
|
||||
Buffer.BlockCopy(getData, StartIndex + 4, getData_span, 0, CoreLenght);
|
||||
DataCallBackReady(getData_span);
|
||||
|
||||
//用Span
|
||||
Span<byte> getData_span = getData;
|
||||
getData_span = getData_span.Slice(StartIndex + 4, CoreLenght);
|
||||
DataCallBackReady(getData_span.ToArray());
|
||||
|
||||
StartIndex += HeadLength;//当读取一条完整的数据后,读取数据的起始下标应为当前接受到的消息体的长度(当前数据的尾部或下一条消息的首部)
|
||||
}
|
||||
@ -352,7 +298,6 @@ namespace HaoYueNet.ClientNetworkNet.Standard2
|
||||
|
||||
public void LogOut(string Msg)
|
||||
{
|
||||
//Console.WriteLine(Msg);
|
||||
OnLogOut(Msg);
|
||||
}
|
||||
|
||||
|
@ -7,12 +7,12 @@ using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace HaoYueNet.ClientNetworkNet.Standard2.OtherMode
|
||||
namespace HaoYueNet.ClientNetwork.Standard2.OtherMode
|
||||
{
|
||||
public class NetworkHelperCore_ListenerMode
|
||||
{
|
||||
private Socket serversocket;
|
||||
private Dictionary<IntPtr, Socket> mDictHandleClient;
|
||||
private Dictionary<nint, Socket> mDictHandleClient;
|
||||
|
||||
//响应倒计时计数最大值
|
||||
private static int MaxRevIndexNum = 50;
|
||||
@ -33,7 +33,7 @@ namespace HaoYueNet.ClientNetworkNet.Standard2.OtherMode
|
||||
|
||||
public void Init(int port)
|
||||
{
|
||||
mDictHandleClient = new Dictionary<IntPtr, Socket>();
|
||||
mDictHandleClient = new Dictionary<nint, Socket>();
|
||||
|
||||
LogOut("==>初始化NetworkHelperCore_ListenerMode");
|
||||
serversocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
||||
@ -69,7 +69,7 @@ namespace HaoYueNet.ClientNetworkNet.Standard2.OtherMode
|
||||
task.Start();
|
||||
}
|
||||
|
||||
#region
|
||||
#region
|
||||
|
||||
/// <summary>
|
||||
/// 追加Socket返回下标
|
||||
@ -97,11 +97,11 @@ namespace HaoYueNet.ClientNetworkNet.Standard2.OtherMode
|
||||
mDictHandleClient.Remove(socket.Handle);
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
#endregion
|
||||
|
||||
~NetworkHelperCore_ListenerMode()
|
||||
{
|
||||
IntPtr[] keys = mDictHandleClient.Keys.ToArray();
|
||||
nint[] keys = mDictHandleClient.Keys.ToArray();
|
||||
for (uint i = 0; i < keys.Length; i++)
|
||||
{
|
||||
mDictHandleClient[keys[i]].Close();
|
||||
@ -115,7 +115,7 @@ namespace HaoYueNet.ClientNetworkNet.Standard2.OtherMode
|
||||
//data = SendDataWithHead(data);
|
||||
try
|
||||
{
|
||||
SendWithIndex(socket,data);
|
||||
SendWithIndex(socket, data);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@ -130,7 +130,7 @@ namespace HaoYueNet.ClientNetworkNet.Standard2.OtherMode
|
||||
/// 发送数据并计数
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
private void SendWithIndex(Socket socket,byte[] data)
|
||||
private void SendWithIndex(Socket socket, byte[] data)
|
||||
{
|
||||
//增加发送计数
|
||||
SendIndex = MaxSendIndexNum;
|
||||
@ -149,7 +149,7 @@ namespace HaoYueNet.ClientNetworkNet.Standard2.OtherMode
|
||||
SendToSocket(socket, data);
|
||||
}
|
||||
|
||||
#region 事件定义
|
||||
#region 事件定义
|
||||
public delegate void OnConnectedHandler(Socket socket);
|
||||
|
||||
public delegate void OnReceiveDataHandler(Socket sk, byte[] data);
|
||||
@ -157,7 +157,7 @@ namespace HaoYueNet.ClientNetworkNet.Standard2.OtherMode
|
||||
public delegate void OnDisconnectHandler(Socket sk);
|
||||
|
||||
public delegate void OnNetLogHandler(string msg);
|
||||
#endregion
|
||||
#endregion
|
||||
|
||||
public event OnConnectedHandler OnConnected;
|
||||
|
||||
@ -187,46 +187,52 @@ namespace HaoYueNet.ClientNetworkNet.Standard2.OtherMode
|
||||
OnCloseReady(socket);
|
||||
}
|
||||
|
||||
private void DataCallBackReady(Socket socket,byte[] data)
|
||||
private void DataCallBackReady(Socket socket, byte[] data)
|
||||
{
|
||||
//增加接收计数
|
||||
RevIndex = MaxRevIndexNum;
|
||||
OnReceive(socket,data);
|
||||
OnReceive(socket, data);
|
||||
}
|
||||
|
||||
MemoryStream reciveMemoryStream = new MemoryStream();//开辟一个内存流
|
||||
byte[] reciveBuffer = new byte[1024 * 1024 * 2];
|
||||
private void Recive(object o)
|
||||
{
|
||||
MemoryStream memoryStream = new MemoryStream();//开辟一个内存流
|
||||
var client = o as Socket;
|
||||
//MemoryStream memoryStream = new MemoryStream();//开辟一个内存流
|
||||
|
||||
while (true)
|
||||
{
|
||||
byte[] buffer = new byte[1024 * 1024 * 2];
|
||||
int effective = 0;
|
||||
try
|
||||
{
|
||||
effective = client.Receive(buffer);
|
||||
if (effective == 0)
|
||||
effective = client.Receive(reciveBuffer);
|
||||
if (effective == 0)//为0表示已经断开连接,放到后面处理
|
||||
{
|
||||
continue;
|
||||
//清理数据
|
||||
reciveMemoryStream.SetLength(0);
|
||||
reciveMemoryStream.Seek(0, SeekOrigin.Begin);
|
||||
//远程主机强迫关闭了一个现有的连接
|
||||
OnCloseReady(client);
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//清理数据
|
||||
reciveMemoryStream.SetLength(0);
|
||||
reciveMemoryStream.Seek(0, SeekOrigin.Begin);
|
||||
|
||||
//远程主机强迫关闭了一个现有的连接
|
||||
OnCloseReady(client);
|
||||
return;
|
||||
//断开连接
|
||||
}
|
||||
if (effective > 0)//如果接受到的消息不为0(不为空)
|
||||
{
|
||||
memoryStream.Write(buffer, 0, effective);//将接受到的数据写入内存流中
|
||||
DataCallBackReady(client, memoryStream.ToArray());
|
||||
|
||||
reciveMemoryStream.Write(reciveBuffer, 0, effective);//将接受到的数据写入内存流中
|
||||
DataCallBackReady(client, reciveMemoryStream.ToArray());
|
||||
//流复用的方式 不用重新new申请
|
||||
memoryStream.Position = 0;
|
||||
memoryStream.SetLength(0);
|
||||
}
|
||||
reciveMemoryStream.Position = 0;
|
||||
reciveMemoryStream.SetLength(0);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -3,9 +3,9 @@ using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
using static HaoYueNet.ClientNetworkNet.Standard2.BaseData;
|
||||
using static HaoYueNet.ClientNetwork.Standard2.BaseData;
|
||||
|
||||
namespace HaoYueNet.ClientNetworkNet.Standard2.OtherMode
|
||||
namespace HaoYueNet.ClientNetwork.Standard2.OtherMode
|
||||
{
|
||||
public class NetworkHelperCore_SourceMode
|
||||
{
|
||||
@ -195,39 +195,44 @@ namespace HaoYueNet.ClientNetworkNet.Standard2.OtherMode
|
||||
OnReceiveData(data);
|
||||
}
|
||||
|
||||
MemoryStream memoryStream = new MemoryStream();//开辟一个内存流
|
||||
MemoryStream reciveMemoryStream = new MemoryStream();//开辟一个内存流
|
||||
byte[] reciveBuffer = new byte[1024 * 1024 * 2];
|
||||
private void Recive(object o)
|
||||
{
|
||||
var client = o as Socket;
|
||||
//MemoryStream memoryStream = new MemoryStream();//开辟一个内存流
|
||||
|
||||
while (true)
|
||||
{
|
||||
byte[] buffer = new byte[1024 * 1024 * 2];
|
||||
int effective = 0;
|
||||
try
|
||||
{
|
||||
effective = client.Receive(buffer);
|
||||
if (effective == 0)
|
||||
effective = client.Receive(reciveBuffer);
|
||||
if (effective == 0)//为0表示已经断开连接,放到后面处理
|
||||
{
|
||||
continue;
|
||||
//尝试性,清理数据
|
||||
reciveMemoryStream.SetLength(0);
|
||||
reciveMemoryStream.Seek(0, SeekOrigin.Begin);
|
||||
//远程主机强迫关闭了一个现有的连接
|
||||
OnCloseReady();
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//尝试性,清理数据
|
||||
reciveMemoryStream.SetLength(0);
|
||||
reciveMemoryStream.Seek(0, SeekOrigin.Begin);
|
||||
|
||||
//断开连接
|
||||
//远程主机强迫关闭了一个现有的连接
|
||||
OnCloseReady();
|
||||
return;
|
||||
//断开连接
|
||||
}
|
||||
if (effective > 0)//如果接受到的消息不为0(不为空)
|
||||
{
|
||||
memoryStream.Write(buffer, 0, effective);//将接受到的数据写入内存流中
|
||||
DataCallBackReady(memoryStream.ToArray());
|
||||
|
||||
reciveMemoryStream.Write(reciveBuffer, 0, effective);//将接受到的数据写入内存流中
|
||||
DataCallBackReady(reciveMemoryStream.ToArray());
|
||||
//流复用的方式 不用重新new申请
|
||||
memoryStream.Position = 0;
|
||||
memoryStream.SetLength(0);
|
||||
}
|
||||
reciveMemoryStream.Position = 0;
|
||||
reciveMemoryStream.SetLength(0);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -55,7 +55,7 @@ namespace HaoYueNet.ServerNetwork.Standard2
|
||||
writeUInt16(BufferData, 4, CmdID);
|
||||
|
||||
//Error
|
||||
writeUInt16(BufferData, 4 + 2, CmdID);
|
||||
writeUInt16(BufferData, 4 + 2, Error);
|
||||
|
||||
//DATA
|
||||
Buffer.BlockCopy(AddonBytes_Data, 0, BufferData, 4 + 2 + 2, AddonBytes_Data.Length);
|
||||
|
@ -1,6 +1,7 @@
|
||||
//using HunterProtobufCore;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
@ -233,7 +234,11 @@ namespace HaoYueNet.ServerNetwork.Standard2
|
||||
#region Token管理
|
||||
public AsyncUserToken GetAsyncUserTokenForSocket(Socket sk)
|
||||
{
|
||||
return _DictSocketAsyncUserToken.ContainsKey(sk) ? _DictSocketAsyncUserToken[sk] : null;
|
||||
AsyncUserToken result;
|
||||
if (_DictSocketAsyncUserToken.TryGetValue(sk, out result))
|
||||
return result;
|
||||
return null;
|
||||
//return _DictSocketAsyncUserToken.ContainsKey(sk) ? _DictSocketAsyncUserToken[sk] : null;
|
||||
}
|
||||
void AddUserToken(AsyncUserToken userToken)
|
||||
{
|
||||
@ -416,6 +421,9 @@ namespace HaoYueNet.ServerNetwork.Standard2
|
||||
}
|
||||
else
|
||||
{
|
||||
//尝试性,清理数据
|
||||
token.memoryStream.SetLength(0);
|
||||
token.memoryStream.Seek(0, SeekOrigin.Begin);
|
||||
CloseClientSocket(e);
|
||||
}
|
||||
}
|
||||
|
@ -234,7 +234,11 @@ namespace HaoYueNet.ServerNetwork.Standard2
|
||||
#region Token管理
|
||||
public AsyncUserToken GetAsyncUserTokenForSocket(Socket sk)
|
||||
{
|
||||
return _DictSocketAsyncUserToken.ContainsKey(sk) ? _DictSocketAsyncUserToken[sk] : null;
|
||||
AsyncUserToken result;
|
||||
if (_DictSocketAsyncUserToken.TryGetValue(sk, out result))
|
||||
return result;
|
||||
return null;
|
||||
//return _DictSocketAsyncUserToken.ContainsKey(sk) ? _DictSocketAsyncUserToken[sk] : null;
|
||||
}
|
||||
void AddUserToken(AsyncUserToken userToken)
|
||||
{
|
||||
@ -457,6 +461,9 @@ namespace HaoYueNet.ServerNetwork.Standard2
|
||||
}
|
||||
else
|
||||
{
|
||||
//尝试性,清理数据
|
||||
token.memoryStream.SetLength(0);
|
||||
token.memoryStream.Seek(0, SeekOrigin.Begin);
|
||||
CloseClientSocket(e);
|
||||
}
|
||||
}
|
||||
|
@ -1,506 +0,0 @@
|
||||
//// <auto-generated>
|
||||
//// Generated by the protocol buffer compiler. DO NOT EDIT!
|
||||
//// source: protobuf_HunterNetCore.proto
|
||||
//// </auto-generated>
|
||||
//#pragma warning disable 1591, 0612, 3021
|
||||
//#region Designer generated code
|
||||
|
||||
//using pb = global::Google.Protobuf;
|
||||
//using pbc = global::Google.Protobuf.Collections;
|
||||
//using pbr = global::Google.Protobuf.Reflection;
|
||||
//using scg = global::System.Collections.Generic;
|
||||
//namespace HunterProtobufCore {
|
||||
|
||||
// /// <summary>Holder for reflection information generated from protobuf_HunterNetCore.proto</summary>
|
||||
// public static partial class ProtobufHunterNetCoreReflection {
|
||||
|
||||
// #region Descriptor
|
||||
// /// <summary>File descriptor for protobuf_HunterNetCore.proto</summary>
|
||||
// public static pbr::FileDescriptor Descriptor {
|
||||
// get { return descriptor; }
|
||||
// }
|
||||
// private static pbr::FileDescriptor descriptor;
|
||||
|
||||
// static ProtobufHunterNetCoreReflection() {
|
||||
// byte[] descriptorData = global::System.Convert.FromBase64String(
|
||||
// string.Concat(
|
||||
// "Chxwcm90b2J1Zl9IdW50ZXJOZXRDb3JlLnByb3RvEhJIdW50ZXJQcm90b2J1",
|
||||
// "ZkNvcmUiSAoNSHVudGVyTmV0X0MyUxIbChNIdW50ZXJOZXRDb3JlX0NtZElE",
|
||||
// "GAEgASgFEhoKEkh1bnRlck5ldENvcmVfRGF0YRgCIAEoDCJpCg1IdW50ZXJO",
|
||||
// "ZXRfUzJDEhsKE0h1bnRlck5ldENvcmVfQ21kSUQYASABKAUSHwoXSHVudGVy",
|
||||
// "TmV0Q29yZV9FUlJPUkNvZGUYAiABKAUSGgoSSHVudGVyTmV0Q29yZV9EYXRh",
|
||||
// "GAMgASgMQgJIAWIGcHJvdG8z"));
|
||||
// descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
|
||||
// new pbr::FileDescriptor[] { },
|
||||
// new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
|
||||
// new pbr::GeneratedClrTypeInfo(typeof(global::HunterProtobufCore.HunterNet_C2S), global::HunterProtobufCore.HunterNet_C2S.Parser, new[]{ "HunterNetCoreCmdID", "HunterNetCoreData" }, null, null, null, null),
|
||||
// new pbr::GeneratedClrTypeInfo(typeof(global::HunterProtobufCore.HunterNet_S2C), global::HunterProtobufCore.HunterNet_S2C.Parser, new[]{ "HunterNetCoreCmdID", "HunterNetCoreERRORCode", "HunterNetCoreData" }, null, null, null, null)
|
||||
// }));
|
||||
// }
|
||||
// #endregion
|
||||
|
||||
// }
|
||||
// #region Messages
|
||||
// /// <summary>
|
||||
// ///上行
|
||||
// /// </summary>
|
||||
// public sealed partial class HunterNet_C2S : pb::IMessage<HunterNet_C2S>
|
||||
// #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
|
||||
// , pb::IBufferMessage
|
||||
// #endif
|
||||
// {
|
||||
// private static readonly pb::MessageParser<HunterNet_C2S> _parser = new pb::MessageParser<HunterNet_C2S>(() => new HunterNet_C2S());
|
||||
// private pb::UnknownFieldSet _unknownFields;
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public static pb::MessageParser<HunterNet_C2S> Parser { get { return _parser; } }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public static pbr::MessageDescriptor Descriptor {
|
||||
// get { return global::HunterProtobufCore.ProtobufHunterNetCoreReflection.Descriptor.MessageTypes[0]; }
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// pbr::MessageDescriptor pb::IMessage.Descriptor {
|
||||
// get { return Descriptor; }
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public HunterNet_C2S() {
|
||||
// OnConstruction();
|
||||
// }
|
||||
|
||||
// partial void OnConstruction();
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public HunterNet_C2S(HunterNet_C2S other) : this() {
|
||||
// hunterNetCoreCmdID_ = other.hunterNetCoreCmdID_;
|
||||
// hunterNetCoreData_ = other.hunterNetCoreData_;
|
||||
// _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public HunterNet_C2S Clone() {
|
||||
// return new HunterNet_C2S(this);
|
||||
// }
|
||||
|
||||
// /// <summary>Field number for the "HunterNetCore_CmdID" field.</summary>
|
||||
// public const int HunterNetCoreCmdIDFieldNumber = 1;
|
||||
// private int hunterNetCoreCmdID_;
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public int HunterNetCoreCmdID {
|
||||
// get { return hunterNetCoreCmdID_; }
|
||||
// set {
|
||||
// hunterNetCoreCmdID_ = value;
|
||||
// }
|
||||
// }
|
||||
|
||||
// /// <summary>Field number for the "HunterNetCore_Data" field.</summary>
|
||||
// public const int HunterNetCoreDataFieldNumber = 2;
|
||||
// private pb::ByteString hunterNetCoreData_ = pb::ByteString.Empty;
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public pb::ByteString HunterNetCoreData {
|
||||
// get { return hunterNetCoreData_; }
|
||||
// set {
|
||||
// hunterNetCoreData_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
|
||||
// }
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public override bool Equals(object other) {
|
||||
// return Equals(other as HunterNet_C2S);
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public bool Equals(HunterNet_C2S other) {
|
||||
// if (ReferenceEquals(other, null)) {
|
||||
// return false;
|
||||
// }
|
||||
// if (ReferenceEquals(other, this)) {
|
||||
// return true;
|
||||
// }
|
||||
// if (HunterNetCoreCmdID != other.HunterNetCoreCmdID) return false;
|
||||
// if (HunterNetCoreData != other.HunterNetCoreData) return false;
|
||||
// return Equals(_unknownFields, other._unknownFields);
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public override int GetHashCode() {
|
||||
// int hash = 1;
|
||||
// if (HunterNetCoreCmdID != 0) hash ^= HunterNetCoreCmdID.GetHashCode();
|
||||
// if (HunterNetCoreData.Length != 0) hash ^= HunterNetCoreData.GetHashCode();
|
||||
// if (_unknownFields != null) {
|
||||
// hash ^= _unknownFields.GetHashCode();
|
||||
// }
|
||||
// return hash;
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public override string ToString() {
|
||||
// return pb::JsonFormatter.ToDiagnosticString(this);
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public void WriteTo(pb::CodedOutputStream output) {
|
||||
// #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
|
||||
// output.WriteRawMessage(this);
|
||||
// #else
|
||||
// if (HunterNetCoreCmdID != 0) {
|
||||
// output.WriteRawTag(8);
|
||||
// output.WriteInt32(HunterNetCoreCmdID);
|
||||
// }
|
||||
// if (HunterNetCoreData.Length != 0) {
|
||||
// output.WriteRawTag(18);
|
||||
// output.WriteBytes(HunterNetCoreData);
|
||||
// }
|
||||
// if (_unknownFields != null) {
|
||||
// _unknownFields.WriteTo(output);
|
||||
// }
|
||||
// #endif
|
||||
// }
|
||||
|
||||
// #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
|
||||
// if (HunterNetCoreCmdID != 0) {
|
||||
// output.WriteRawTag(8);
|
||||
// output.WriteInt32(HunterNetCoreCmdID);
|
||||
// }
|
||||
// if (HunterNetCoreData.Length != 0) {
|
||||
// output.WriteRawTag(18);
|
||||
// output.WriteBytes(HunterNetCoreData);
|
||||
// }
|
||||
// if (_unknownFields != null) {
|
||||
// _unknownFields.WriteTo(ref output);
|
||||
// }
|
||||
// }
|
||||
// #endif
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public int CalculateSize() {
|
||||
// int size = 0;
|
||||
// if (HunterNetCoreCmdID != 0) {
|
||||
// size += 1 + pb::CodedOutputStream.ComputeInt32Size(HunterNetCoreCmdID);
|
||||
// }
|
||||
// if (HunterNetCoreData.Length != 0) {
|
||||
// size += 1 + pb::CodedOutputStream.ComputeBytesSize(HunterNetCoreData);
|
||||
// }
|
||||
// if (_unknownFields != null) {
|
||||
// size += _unknownFields.CalculateSize();
|
||||
// }
|
||||
// return size;
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public void MergeFrom(HunterNet_C2S other) {
|
||||
// if (other == null) {
|
||||
// return;
|
||||
// }
|
||||
// if (other.HunterNetCoreCmdID != 0) {
|
||||
// HunterNetCoreCmdID = other.HunterNetCoreCmdID;
|
||||
// }
|
||||
// if (other.HunterNetCoreData.Length != 0) {
|
||||
// HunterNetCoreData = other.HunterNetCoreData;
|
||||
// }
|
||||
// _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public void MergeFrom(pb::CodedInputStream input) {
|
||||
// #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
|
||||
// input.ReadRawMessage(this);
|
||||
// #else
|
||||
// uint tag;
|
||||
// while ((tag = input.ReadTag()) != 0) {
|
||||
// switch(tag) {
|
||||
// default:
|
||||
// _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
|
||||
// break;
|
||||
// case 8: {
|
||||
// HunterNetCoreCmdID = input.ReadInt32();
|
||||
// break;
|
||||
// }
|
||||
// case 18: {
|
||||
// HunterNetCoreData = input.ReadBytes();
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// #endif
|
||||
// }
|
||||
|
||||
// #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
|
||||
// uint tag;
|
||||
// while ((tag = input.ReadTag()) != 0) {
|
||||
// switch(tag) {
|
||||
// default:
|
||||
// _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
|
||||
// break;
|
||||
// case 8: {
|
||||
// HunterNetCoreCmdID = input.ReadInt32();
|
||||
// break;
|
||||
// }
|
||||
// case 18: {
|
||||
// HunterNetCoreData = input.ReadBytes();
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// #endif
|
||||
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// ///下行
|
||||
// /// </summary>
|
||||
// public sealed partial class HunterNet_S2C : pb::IMessage<HunterNet_S2C>
|
||||
// #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
|
||||
// , pb::IBufferMessage
|
||||
// #endif
|
||||
// {
|
||||
// private static readonly pb::MessageParser<HunterNet_S2C> _parser = new pb::MessageParser<HunterNet_S2C>(() => new HunterNet_S2C());
|
||||
// private pb::UnknownFieldSet _unknownFields;
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public static pb::MessageParser<HunterNet_S2C> Parser { get { return _parser; } }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public static pbr::MessageDescriptor Descriptor {
|
||||
// get { return global::HunterProtobufCore.ProtobufHunterNetCoreReflection.Descriptor.MessageTypes[1]; }
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// pbr::MessageDescriptor pb::IMessage.Descriptor {
|
||||
// get { return Descriptor; }
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public HunterNet_S2C() {
|
||||
// OnConstruction();
|
||||
// }
|
||||
|
||||
// partial void OnConstruction();
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public HunterNet_S2C(HunterNet_S2C other) : this() {
|
||||
// hunterNetCoreCmdID_ = other.hunterNetCoreCmdID_;
|
||||
// hunterNetCoreERRORCode_ = other.hunterNetCoreERRORCode_;
|
||||
// hunterNetCoreData_ = other.hunterNetCoreData_;
|
||||
// _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public HunterNet_S2C Clone() {
|
||||
// return new HunterNet_S2C(this);
|
||||
// }
|
||||
|
||||
// /// <summary>Field number for the "HunterNetCore_CmdID" field.</summary>
|
||||
// public const int HunterNetCoreCmdIDFieldNumber = 1;
|
||||
// private int hunterNetCoreCmdID_;
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public int HunterNetCoreCmdID {
|
||||
// get { return hunterNetCoreCmdID_; }
|
||||
// set {
|
||||
// hunterNetCoreCmdID_ = value;
|
||||
// }
|
||||
// }
|
||||
|
||||
// /// <summary>Field number for the "HunterNetCore_ERRORCode" field.</summary>
|
||||
// public const int HunterNetCoreERRORCodeFieldNumber = 2;
|
||||
// private int hunterNetCoreERRORCode_;
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public int HunterNetCoreERRORCode {
|
||||
// get { return hunterNetCoreERRORCode_; }
|
||||
// set {
|
||||
// hunterNetCoreERRORCode_ = value;
|
||||
// }
|
||||
// }
|
||||
|
||||
// /// <summary>Field number for the "HunterNetCore_Data" field.</summary>
|
||||
// public const int HunterNetCoreDataFieldNumber = 3;
|
||||
// private pb::ByteString hunterNetCoreData_ = pb::ByteString.Empty;
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public pb::ByteString HunterNetCoreData {
|
||||
// get { return hunterNetCoreData_; }
|
||||
// set {
|
||||
// hunterNetCoreData_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
|
||||
// }
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public override bool Equals(object other) {
|
||||
// return Equals(other as HunterNet_S2C);
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public bool Equals(HunterNet_S2C other) {
|
||||
// if (ReferenceEquals(other, null)) {
|
||||
// return false;
|
||||
// }
|
||||
// if (ReferenceEquals(other, this)) {
|
||||
// return true;
|
||||
// }
|
||||
// if (HunterNetCoreCmdID != other.HunterNetCoreCmdID) return false;
|
||||
// if (HunterNetCoreERRORCode != other.HunterNetCoreERRORCode) return false;
|
||||
// if (HunterNetCoreData != other.HunterNetCoreData) return false;
|
||||
// return Equals(_unknownFields, other._unknownFields);
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public override int GetHashCode() {
|
||||
// int hash = 1;
|
||||
// if (HunterNetCoreCmdID != 0) hash ^= HunterNetCoreCmdID.GetHashCode();
|
||||
// if (HunterNetCoreERRORCode != 0) hash ^= HunterNetCoreERRORCode.GetHashCode();
|
||||
// if (HunterNetCoreData.Length != 0) hash ^= HunterNetCoreData.GetHashCode();
|
||||
// if (_unknownFields != null) {
|
||||
// hash ^= _unknownFields.GetHashCode();
|
||||
// }
|
||||
// return hash;
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public override string ToString() {
|
||||
// return pb::JsonFormatter.ToDiagnosticString(this);
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public void WriteTo(pb::CodedOutputStream output) {
|
||||
// #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
|
||||
// output.WriteRawMessage(this);
|
||||
// #else
|
||||
// if (HunterNetCoreCmdID != 0) {
|
||||
// output.WriteRawTag(8);
|
||||
// output.WriteInt32(HunterNetCoreCmdID);
|
||||
// }
|
||||
// if (HunterNetCoreERRORCode != 0) {
|
||||
// output.WriteRawTag(16);
|
||||
// output.WriteInt32(HunterNetCoreERRORCode);
|
||||
// }
|
||||
// if (HunterNetCoreData.Length != 0) {
|
||||
// output.WriteRawTag(26);
|
||||
// output.WriteBytes(HunterNetCoreData);
|
||||
// }
|
||||
// if (_unknownFields != null) {
|
||||
// _unknownFields.WriteTo(output);
|
||||
// }
|
||||
// #endif
|
||||
// }
|
||||
|
||||
// #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
|
||||
// if (HunterNetCoreCmdID != 0) {
|
||||
// output.WriteRawTag(8);
|
||||
// output.WriteInt32(HunterNetCoreCmdID);
|
||||
// }
|
||||
// if (HunterNetCoreERRORCode != 0) {
|
||||
// output.WriteRawTag(16);
|
||||
// output.WriteInt32(HunterNetCoreERRORCode);
|
||||
// }
|
||||
// if (HunterNetCoreData.Length != 0) {
|
||||
// output.WriteRawTag(26);
|
||||
// output.WriteBytes(HunterNetCoreData);
|
||||
// }
|
||||
// if (_unknownFields != null) {
|
||||
// _unknownFields.WriteTo(ref output);
|
||||
// }
|
||||
// }
|
||||
// #endif
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public int CalculateSize() {
|
||||
// int size = 0;
|
||||
// if (HunterNetCoreCmdID != 0) {
|
||||
// size += 1 + pb::CodedOutputStream.ComputeInt32Size(HunterNetCoreCmdID);
|
||||
// }
|
||||
// if (HunterNetCoreERRORCode != 0) {
|
||||
// size += 1 + pb::CodedOutputStream.ComputeInt32Size(HunterNetCoreERRORCode);
|
||||
// }
|
||||
// if (HunterNetCoreData.Length != 0) {
|
||||
// size += 1 + pb::CodedOutputStream.ComputeBytesSize(HunterNetCoreData);
|
||||
// }
|
||||
// if (_unknownFields != null) {
|
||||
// size += _unknownFields.CalculateSize();
|
||||
// }
|
||||
// return size;
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public void MergeFrom(HunterNet_S2C other) {
|
||||
// if (other == null) {
|
||||
// return;
|
||||
// }
|
||||
// if (other.HunterNetCoreCmdID != 0) {
|
||||
// HunterNetCoreCmdID = other.HunterNetCoreCmdID;
|
||||
// }
|
||||
// if (other.HunterNetCoreERRORCode != 0) {
|
||||
// HunterNetCoreERRORCode = other.HunterNetCoreERRORCode;
|
||||
// }
|
||||
// if (other.HunterNetCoreData.Length != 0) {
|
||||
// HunterNetCoreData = other.HunterNetCoreData;
|
||||
// }
|
||||
// _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
|
||||
// }
|
||||
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// public void MergeFrom(pb::CodedInputStream input) {
|
||||
// #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
|
||||
// input.ReadRawMessage(this);
|
||||
// #else
|
||||
// uint tag;
|
||||
// while ((tag = input.ReadTag()) != 0) {
|
||||
// switch(tag) {
|
||||
// default:
|
||||
// _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
|
||||
// break;
|
||||
// case 8: {
|
||||
// HunterNetCoreCmdID = input.ReadInt32();
|
||||
// break;
|
||||
// }
|
||||
// case 16: {
|
||||
// HunterNetCoreERRORCode = input.ReadInt32();
|
||||
// break;
|
||||
// }
|
||||
// case 26: {
|
||||
// HunterNetCoreData = input.ReadBytes();
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// #endif
|
||||
// }
|
||||
|
||||
// #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
|
||||
// [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
|
||||
// void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
|
||||
// uint tag;
|
||||
// while ((tag = input.ReadTag()) != 0) {
|
||||
// switch(tag) {
|
||||
// default:
|
||||
// _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
|
||||
// break;
|
||||
// case 8: {
|
||||
// HunterNetCoreCmdID = input.ReadInt32();
|
||||
// break;
|
||||
// }
|
||||
// case 16: {
|
||||
// HunterNetCoreERRORCode = input.ReadInt32();
|
||||
// break;
|
||||
// }
|
||||
// case 26: {
|
||||
// HunterNetCoreData = input.ReadBytes();
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// #endif
|
||||
|
||||
// }
|
||||
|
||||
// #endregion
|
||||
|
||||
//}
|
||||
|
||||
//#endregion Designer generated code
|
19
README.md
19
README.md
@ -1,17 +1,17 @@
|
||||
# HaoYueNet
|
||||
|
||||
.Net 8 的,自建基于IOCP的TCP的高性能网络库
|
||||
.Net8/.NetStandard2.0 的,泛用形自建高性能网络库
|
||||
|
||||
使用Protobuff作为基础协议(网络库本身不依赖Protobuff,仅上层示例依赖)
|
||||
基于IOCP进一步深度优化而来
|
||||
|
||||
网络库本身无依赖,可以用于任何数据通讯
|
||||
|
||||
包含服务端和客户端双端库,可直接用于各类.Net程序或Unity程序,做TCP通讯底层库。
|
||||
|
||||
并包含心跳包等检测、连接管理、Protobuff解析,优化后的高性能收发等等。
|
||||
网络库本身无依赖,可以用于任何数据通讯 (网络库本身不依赖Protobuff,仅上层示例依赖)
|
||||
|
||||
不用关心网络底层,直接引用或继承,即可便捷使用。
|
||||
|
||||
示例demo中,包含服务端和客户端双端库,可直接用于各类.Net版本程序或Unity程序,做TCP通讯底层库。
|
||||
|
||||
并包含心跳包等检测、连接管理、Protobuff解析,优化后的高性能收发等等。
|
||||
|
||||
#使用基础事件回调即可:
|
||||
|
||||
OnClientNumberChange//连接数发生变化
|
||||
@ -23,6 +23,7 @@ OnNetLog//来自网络库的日志信息
|
||||
OnReceive//收到网络数据
|
||||
|
||||
#Simple目录下,有实例客户端和实例服务端
|
||||
|
||||
示例中,使用本网络库,您可以继续示例项目写,也可以参照示例代码。
|
||||
|
||||
实现了:
|
||||
@ -90,6 +91,6 @@ HaoYueNet.ServerNetwork.dll
|
||||
|
||||
客户端
|
||||
|
||||
HaoYueNet.ClientNetwork.dll (.net7 推荐跨平台.net程序使用)
|
||||
HaoYueNet.ClientNetwork.dll (.net8 推荐跨平台.net程序使用)
|
||||
|
||||
HaoYueNet.ClientNetworkNet4x.dll (传统.Net4.X版本,用于传统.NetFX程序或Unity游戏,或Mono程序)
|
||||
HaoYueNet.ClientNetworkNet.Standard2.dll (.NetStandard 2.0标准的库,用于各种.Net运行时,传统.Net4.X版本,用于传统.NetFX程序或Unity游戏,或Mono程序)
|
||||
|
@ -63,17 +63,29 @@
|
||||
|
||||
private void InterRegisterEvent(EEvent evt, Delegate callback)
|
||||
{
|
||||
if (eventDic.ContainsKey(evt))
|
||||
if (eventDic.TryGetValue(evt, out List<Delegate> dlist))
|
||||
{
|
||||
if (eventDic[evt].IndexOf(callback) < 0)
|
||||
if (dlist.IndexOf(callback) < 0)
|
||||
{
|
||||
eventDic[evt].Add(callback);
|
||||
dlist.Add(callback);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
eventDic.Add(evt, new List<Delegate>() { callback });
|
||||
}
|
||||
|
||||
//if (eventDic.ContainsKey(evt))
|
||||
//{
|
||||
// if (eventDic[evt].IndexOf(callback) < 0)
|
||||
// {
|
||||
// eventDic[evt].Add(callback);
|
||||
// }
|
||||
//}
|
||||
//else
|
||||
//{
|
||||
// eventDic.Add(evt, new List<Delegate>() { callback });
|
||||
//}
|
||||
}
|
||||
#endregion
|
||||
|
||||
@ -111,11 +123,16 @@
|
||||
|
||||
private void InterUnregisterEvent(EEvent evt, Delegate callback)
|
||||
{
|
||||
if (eventDic.ContainsKey(evt))
|
||||
if (eventDic.TryGetValue(evt, out List<Delegate> dlist))
|
||||
{
|
||||
eventDic[evt].Remove(callback);
|
||||
if (eventDic[evt].Count == 0) eventDic.Remove(evt);
|
||||
dlist.Remove(callback);
|
||||
if (dlist.Count == 0) eventDic.Remove(evt);
|
||||
}
|
||||
//if (eventDic.ContainsKey(evt))
|
||||
//{
|
||||
// eventDic[evt].Remove(callback);
|
||||
// if (eventDic[evt].Count == 0) eventDic.Remove(evt);
|
||||
//}
|
||||
}
|
||||
#endregion
|
||||
|
||||
@ -224,14 +241,21 @@
|
||||
/// <returns></returns>
|
||||
private List<Delegate> GetEventList(EEvent evt)
|
||||
{
|
||||
if (eventDic.ContainsKey(evt))
|
||||
if (eventDic.TryGetValue(evt,out List<Delegate> dlist))
|
||||
{
|
||||
List<Delegate> tempList = eventDic[evt];
|
||||
if (null != tempList)
|
||||
if (null != dlist)
|
||||
{
|
||||
return tempList;
|
||||
return dlist;
|
||||
}
|
||||
}
|
||||
//if (eventDic.ContainsKey(evt))
|
||||
//{
|
||||
// List<Delegate> tempList = eventDic[evt];
|
||||
// if (null != tempList)
|
||||
// {
|
||||
// return tempList;
|
||||
// }
|
||||
//}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
@ -20,17 +20,28 @@
|
||||
|
||||
private void InterRegNetMsgEvent(int cmd, Delegate callback)
|
||||
{
|
||||
if (netEventDic.ContainsKey(cmd))
|
||||
if (netEventDic.TryGetValue(cmd, out List<Delegate> dlist))
|
||||
{
|
||||
if (netEventDic[cmd].IndexOf(callback) < 0)
|
||||
if (dlist.IndexOf(callback) < 0)
|
||||
{
|
||||
netEventDic[cmd].Add(callback);
|
||||
dlist.Add(callback);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
netEventDic.Add(cmd, new List<Delegate>() { callback });
|
||||
}
|
||||
//if (netEventDic.ContainsKey(cmd))
|
||||
//{
|
||||
// if (netEventDic[cmd].IndexOf(callback) < 0)
|
||||
// {
|
||||
// netEventDic[cmd].Add(callback);
|
||||
// }
|
||||
//}
|
||||
//else
|
||||
//{
|
||||
// netEventDic.Add(cmd, new List<Delegate>() { callback });
|
||||
//}
|
||||
}
|
||||
#endregion
|
||||
|
||||
@ -44,11 +55,16 @@
|
||||
|
||||
private void InterUnregisterCMD(int cmd, Delegate callback)
|
||||
{
|
||||
if (netEventDic.ContainsKey(cmd))
|
||||
if (netEventDic.TryGetValue(cmd, out List<Delegate> dlist))
|
||||
{
|
||||
netEventDic[cmd].Remove(callback);
|
||||
if (netEventDic[cmd].Count == 0) netEventDic.Remove(cmd);
|
||||
dlist.Remove(callback);
|
||||
if (dlist.Count == 0) netEventDic.Remove(cmd);
|
||||
}
|
||||
//if (netEventDic.ContainsKey(cmd))
|
||||
//{
|
||||
// netEventDic[cmd].Remove(callback);
|
||||
// if (netEventDic[cmd].Count == 0) netEventDic.Remove(cmd);
|
||||
//}
|
||||
}
|
||||
#endregion
|
||||
|
||||
@ -80,14 +96,22 @@
|
||||
/// <returns></returns>
|
||||
private List<Delegate> GetNetEventDicList(int cmd)
|
||||
{
|
||||
if (netEventDic.ContainsKey(cmd))
|
||||
|
||||
if (netEventDic.TryGetValue(cmd, out List<Delegate> dlist))
|
||||
{
|
||||
List<Delegate> tempList = netEventDic[cmd];
|
||||
if (null != tempList)
|
||||
if (null != dlist)
|
||||
{
|
||||
return tempList;
|
||||
return dlist;
|
||||
}
|
||||
}
|
||||
//if (netEventDic.ContainsKey(cmd))
|
||||
//{
|
||||
// List<Delegate> tempList = netEventDic[cmd];
|
||||
// if (null != tempList)
|
||||
// {
|
||||
// return tempList;
|
||||
// }
|
||||
//}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
14
Simple/ClientSaeaTest/ClientSaeaTest.csproj
Normal file
14
Simple/ClientSaeaTest/ClientSaeaTest.csproj
Normal file
@ -0,0 +1,14 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\NetLib\HaoYueNet.ClientNetwork\HaoYueNet.ClientNetwork.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
19
Simple/ClientSaeaTest/Program.cs
Normal file
19
Simple/ClientSaeaTest/Program.cs
Normal file
@ -0,0 +1,19 @@
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace ClientSaeaTest
|
||||
{
|
||||
internal class Program
|
||||
{
|
||||
static SaeaClient client = new SaeaClient(1024,1024);
|
||||
static void Main(string[] args)
|
||||
{
|
||||
client.Init();
|
||||
client.Start();
|
||||
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
||||
client.Connect("139.186.160.243",1000);
|
||||
|
||||
Console.WriteLine("Hello, World!");
|
||||
Console.ReadLine();
|
||||
}
|
||||
}
|
||||
}
|
69
Simple/ClientSaeaTest/SaeaClient.cs
Normal file
69
Simple/ClientSaeaTest/SaeaClient.cs
Normal file
@ -0,0 +1,69 @@
|
||||
using HaoYueNet.ClientNetwork.IOCPMode;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace ClientSaeaTest
|
||||
{
|
||||
internal class SaeaClient : TcpSaeaClient
|
||||
{
|
||||
public SaeaClient(int numConnections, int receiveBufferSize)
|
||||
: base(numConnections, receiveBufferSize)
|
||||
{
|
||||
OnClientNumberChange += ClientNumberChange;
|
||||
OnReceive += ReceiveData;
|
||||
OnDisconnected += OnDisconnect;
|
||||
OnNetLog += OnShowNetLog;
|
||||
}
|
||||
|
||||
|
||||
private void ClientNumberChange(int num, AsyncUserToken token)
|
||||
{
|
||||
Console.WriteLine("Client数发生变化");
|
||||
}
|
||||
|
||||
public void Connect(string ip, int port)
|
||||
{
|
||||
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
||||
base.StartConnect(ip, port, socket);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 接受包回调
|
||||
/// </summary>
|
||||
/// <param name="CMDID">协议ID</param>
|
||||
/// <param name="ERRCODE">错误编号</param>
|
||||
/// <param name="data">业务数据</param>
|
||||
private void ReceiveData(AsyncUserToken token, int CMDID,int Error, byte[] data)
|
||||
{
|
||||
DataCallBack(token.Socket, CMDID, Error,data);
|
||||
}
|
||||
|
||||
public void DataCallBack(Socket sk, int CMDID, int Error, byte[] data)
|
||||
{
|
||||
Console.WriteLine("收到消息 CMDID =>" + CMDID + " 数据长度=>" + data.Length);
|
||||
try
|
||||
{
|
||||
//抛出网络数据
|
||||
//NetMsg.Instance.PostNetMsgEvent(CMDID, sk, data);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine("逻辑处理错误:" + ex.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 断开连接
|
||||
/// </summary>
|
||||
/// <param name="sk"></param>
|
||||
public void OnDisconnect(AsyncUserToken token)
|
||||
{
|
||||
Console.WriteLine("断开连接");
|
||||
//ServerManager.g_ClientMgr.SetClientOfflineForSocket(token.Socket);
|
||||
}
|
||||
|
||||
public void OnShowNetLog(string msg)
|
||||
{
|
||||
//ServerManager.g_Log.Debug(msg);
|
||||
}
|
||||
}
|
||||
}
|
@ -202,14 +202,21 @@ namespace ServerCore.Event
|
||||
/// <returns></returns>
|
||||
private List<Delegate> GetEventList(EEvent evt)
|
||||
{
|
||||
if (eventDic.ContainsKey(evt))
|
||||
if (eventDic.TryGetValue(evt, out List<Delegate> dlist))
|
||||
{
|
||||
List<Delegate> tempList = eventDic[evt];
|
||||
if (null != tempList)
|
||||
if (null != dlist)
|
||||
{
|
||||
return tempList;
|
||||
return dlist;
|
||||
}
|
||||
}
|
||||
//if (eventDic.ContainsKey(evt))
|
||||
//{
|
||||
// List<Delegate> tempList = eventDic[evt];
|
||||
// if (null != tempList)
|
||||
// {
|
||||
// return tempList;
|
||||
// }
|
||||
//}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user