├── Examples ├── client.pfx ├── server.pfx └── Examples.csproj ├── Tests ├── ConsoleTest │ ├── client.pfx │ ├── server.pfx │ ├── App.config │ ├── UnitTests │ │ ├── Properties │ │ │ └── AssemblyInfo.cs │ │ └── ByteMessageParserTest.cs │ ├── packages.config │ └── Properties │ │ └── AssemblyInfo.cs └── UnitTests │ ├── client.pfx │ ├── server.pfx │ ├── EncryptionTest.cs │ ├── UnitTests.csproj │ └── MessageTests.cs ├── Benchmarks ├── SslBenchmark │ ├── client.pfx │ ├── server.pfx │ └── SslBenchmark.csproj ├── SslBenchmark2 │ ├── client.pfx │ ├── server.pfx │ └── SslBenchmark2.csproj ├── RelayBenchmark │ ├── client.pfx │ └── RelayBenchmark.csproj ├── SecureProtobuffBenchmark │ ├── client.pfx │ ├── server.pfx │ └── ProtoSecureNetworkBenchmark.csproj ├── RudpBenchmark │ └── RudpBenchmark.csproj ├── HybridProtoNetworkBenchmark │ └── ProtoNetworkBenchmark.csproj ├── TcpBenchmark │ └── TcpMessageBenchmark.csproj └── UdpBenchmark │ └── UdpBenchmark.csproj ├── NetworkLibrary ├── TCP │ ├── SSL │ │ ├── Certificates │ │ │ ├── client.pfx │ │ │ └── server.pfx │ │ └── ByteMessage │ │ │ ├── SsLByteMessageClient.cs │ │ │ ├── SSlByteMessageServer.cs │ │ │ └── SSLByteMessageSession.cs │ ├── ByteMessage │ │ ├── ByteMessageTcpClient.cs │ │ ├── ByteMessageTcpServer.cs │ │ └── ByteMessageSession.cs │ ├── Base │ │ └── Core │ │ │ └── IAsyncSession.cs │ ├── Generic │ │ ├── GenericBuffer.cs │ │ └── GenericSession.cs │ ├── AES │ │ ├── AesTcpServer.cs │ │ └── AesTcpClient.cs │ └── SSLCustom │ │ ├── CustomSslSession.cs │ │ └── CustomSslClient.cs ├── MessageProtocol │ ├── Generic │ │ ├── Interfaces │ │ │ ├── IRouterHeader.cs │ │ │ ├── ISerialisableMessageQueue.cs │ │ │ ├── ISerializer.cs │ │ │ ├── IMessageEnvelope.cs │ │ │ └── IMessageSerialiser.cs │ │ └── Components │ │ │ └── GenericMessageAwaiter.cs │ ├── Serialization │ │ └── RouterHeader.cs │ └── Fast │ │ ├── ISerialisableMessageQueue.cs │ │ ├── IMessageSerializer.cs │ │ └── Wrapper │ │ └── GenericMessageClientWrapper.cs ├── Components │ ├── Crypto │ │ ├── Certificate │ │ │ ├── Native │ │ │ │ ├── KeyType.cs │ │ │ │ ├── KeyExchangeKey.cs │ │ │ │ ├── Win32ErrorHelper.cs │ │ │ │ ├── CryptKey.cs │ │ │ │ ├── CertProperties.cs │ │ │ │ └── DisposableObject.cs │ │ │ └── CertificateGenerator.cs │ │ ├── Algorithms │ │ │ ├── IAesAlgorithm.cs │ │ │ └── NoEncyption.cs │ │ └── IAesEngine.cs │ ├── Statistics │ │ └── TcpClientStatisticsPublisher.cs │ ├── MessageBuffer │ │ ├── Interface │ │ │ └── IMessageProcessQueue.cs │ │ └── MessageQueue.cs │ └── MessageProcessor │ │ └── Interface │ │ └── IMessageProcessor.cs ├── P2P │ ├── RoomServer.cs │ ├── Components │ │ ├── InfoMessages.cs │ │ ├── MockSerializer.cs │ │ ├── HolePunch │ │ │ ├── Messages.cs │ │ │ └── IPUtils.cs │ │ └── StateManagemet │ │ │ └── Server │ │ │ ├── ServerStateManager.cs │ │ │ └── ServerConnectionState.cs │ ├── RelayServer.cs │ └── Constants.cs ├── Utils │ ├── ConcurrentObjectPool.cs │ ├── PrefixWriter.cs │ ├── MiniLogger.cs │ ├── Spinlock.cs │ ├── AsyncManualResetEvent.cs │ ├── ByteCopy.cs │ ├── SharedMemoryStreamPool.cs │ └── AsyncAutoResetEvent.cs ├── UDP │ ├── Reliable │ │ ├── Config │ │ │ └── SenderModuleConfig.cs │ │ ├── Components │ │ │ ├── Segment.cs │ │ │ └── Timer.cs │ │ ├── Helpers │ │ │ └── Compactor.cs │ │ └── Test │ │ │ └── Mockup.cs │ ├── Jumbo │ │ ├── Mock.cs │ │ └── JumboModule.cs │ └── Secure │ │ └── SecureUdpClient.cs ├── NetworkLibrary - Backup.csproj └── NetworkLibrary.csproj ├── Protobuff ├── Components │ ├── IProtoMessage.cs │ ├── ConcurrentProtoSerializer.cs │ └── ProtoSerializer.cs ├── Pure │ ├── PureProtoClient.cs │ ├── PureProtoServer.cs │ ├── PureSecureProtoClient.cs │ └── PureSecureProtoServer.cs ├── P2P │ ├── SecureLobbyClient.cs │ ├── RelayClient.cs │ ├── Generic │ │ ├── InfoMessages.cs │ │ ├── HolePunch │ │ │ └── Messages.cs │ │ ├── Constants.cs │ │ └── StateManagemet │ │ │ └── Server │ │ │ └── ServerStateManager.cs │ └── SecureProtoRelayServer.cs ├── ProtoMessageClient.cs ├── ProtoMessageServer.cs ├── SecureProtoMessageClient.cs ├── SecureProtoMessageServer.cs ├── Protobuff.csproj └── UDP │ ├── GenericSecureUdpMessageClient.cs │ └── EncryptedUdpProtoClient.cs ├── SerializedNetwork ├── HybridProtoNetwork │ ├── HybridNetwork.csproj │ ├── ServerClientSession.cs │ └── Serializer.cs ├── JsonNetwork │ ├── PureJsonClient.cs │ ├── PureJsonServer.cs │ ├── JsonMessageNetwork.csproj │ ├── Internal │ │ └── ClientServer.cs │ ├── Components │ │ └── JsonSerializer.cs │ └── JsonMessageClient.cs ├── MessagePackNetwork │ ├── PureMessagePackClient.cs │ ├── PureMessagePackServer.cs │ ├── MessagePackNetwork.csproj │ ├── Internal │ │ └── ClientServer.cs │ └── Components │ │ ├── MessagePackSerializer.cs │ │ └── BufferWriter.cs ├── BinarySerializerNetwork │ ├── PureBinaryClient.cs │ ├── BinarySerializerNetwork.csproj │ ├── PureBinaryServer.cs │ ├── Internal │ │ └── ServerClientSession.cs │ └── Components │ │ └── BinarySerializer.cs ├── DataContractNetwork │ ├── PureDataContractClient.cs │ ├── DataContractNetwork.csproj │ ├── PureDataContractServer.cs │ ├── Internal │ │ └── ServerClientSession.cs │ └── Components │ │ └── DataContractSerializer.cs ├── CustomSerializer │ ├── CustomSerializer.csproj │ ├── ServerClientSession.cs │ └── Serializer.cs ├── Benchmarks │ ├── JsonMessageBenchmark │ │ └── JsonMessageBenchmark.csproj │ ├── MessagepackBenchmark │ │ └── MessagePackBenchmark.csproj │ ├── ProtobuffBenchmark │ │ └── ProtobuffBenchmark.csproj │ ├── CustomSerializerBenchmark │ │ └── CustomSerializerMessageBenchmark.csproj │ ├── NetSerializerBenchmark │ │ └── NetSerializerBenchmark.csproj │ ├── BinaryMessageBenchmark │ │ └── BinaryMessageBenchmark.csproj │ └── DataContractMessageBenchmark │ │ └── DataContractMessageBenchmark.csproj ├── ProtobufNetwork │ ├── ProtobufNetwork.csproj │ ├── InternalClientServerSessioncs.cs │ ├── ProtoSerializer.cs │ └── ProtoClient.cs └── NetSerializerNetwork │ ├── NetSerializerNetwork.csproj │ ├── Internal │ └── ServerClientSession.cs │ └── Components │ └── NetSerializer.cs ├── Json ├── Pure │ ├── JsonClient.cs │ ├── JsonServer.cs │ ├── SecureJsonClient.cs │ └── SecureJsonServer.cs ├── MessageProtocol │ ├── JsonMessageClient.cs │ ├── JsonMessageServer.cs │ ├── SecureJsonMessageClient.cs │ └── SecureJsonMessageServer.cs ├── P2P │ ├── JsonRelayClient.cs │ └── Room │ │ └── JsonRoomClient.cs ├── Components │ └── JsonSerializer.cs └── JsonNetwork.csproj ├── NetSerializer ├── Pure │ ├── NetSerialiserClient.cs │ ├── NetSerialiserServer.cs │ ├── SecureNetSerialiserClient.cs │ └── SecureNetSerialiserServer.cs ├── MessageProtocol │ ├── NetSerialiserMessageClient.cs │ ├── NetSerialiserMessageServer.cs │ ├── SecureNetSerialiserMessageClient.cs │ └── SecureNetSerialiserMessageServer.cs ├── P2P │ ├── NetSerialiserRelayClient.cs │ └── Room │ │ └── NetSerialiserRoomClient.cs ├── NetSerializerNetwork.csproj └── Components │ └── NetSerialiser.cs ├── MessagePack ├── MessageProtocol │ ├── MessagePackMessageClient.cs │ ├── MessagePackMessageServer.cs │ ├── SecureMessagePackMessageClient.cs │ └── SecureMessagePackMessageServer.cs ├── Pure │ ├── MessagePackClient.cs │ ├── MessagePackServer.cs │ ├── SecureMessagePackClient.cs │ └── SecureMessagePackServer.cs ├── P2P │ ├── Room │ │ └── MessagePackRoomClient.cs │ └── MessagePackRelayClient.cs ├── MessagePackNetwork.csproj └── Components │ └── MessagePackSerializer.cs └── .gitattributes /Examples/client.pfx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReferenceType/StandardNetworkLibrary/HEAD/Examples/client.pfx -------------------------------------------------------------------------------- /Examples/server.pfx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReferenceType/StandardNetworkLibrary/HEAD/Examples/server.pfx -------------------------------------------------------------------------------- /Tests/ConsoleTest/client.pfx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReferenceType/StandardNetworkLibrary/HEAD/Tests/ConsoleTest/client.pfx -------------------------------------------------------------------------------- /Tests/ConsoleTest/server.pfx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReferenceType/StandardNetworkLibrary/HEAD/Tests/ConsoleTest/server.pfx -------------------------------------------------------------------------------- /Tests/UnitTests/client.pfx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReferenceType/StandardNetworkLibrary/HEAD/Tests/UnitTests/client.pfx -------------------------------------------------------------------------------- /Tests/UnitTests/server.pfx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReferenceType/StandardNetworkLibrary/HEAD/Tests/UnitTests/server.pfx -------------------------------------------------------------------------------- /Benchmarks/SslBenchmark/client.pfx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReferenceType/StandardNetworkLibrary/HEAD/Benchmarks/SslBenchmark/client.pfx -------------------------------------------------------------------------------- /Benchmarks/SslBenchmark/server.pfx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReferenceType/StandardNetworkLibrary/HEAD/Benchmarks/SslBenchmark/server.pfx -------------------------------------------------------------------------------- /Benchmarks/SslBenchmark2/client.pfx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReferenceType/StandardNetworkLibrary/HEAD/Benchmarks/SslBenchmark2/client.pfx -------------------------------------------------------------------------------- /Benchmarks/SslBenchmark2/server.pfx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReferenceType/StandardNetworkLibrary/HEAD/Benchmarks/SslBenchmark2/server.pfx -------------------------------------------------------------------------------- /Benchmarks/RelayBenchmark/client.pfx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReferenceType/StandardNetworkLibrary/HEAD/Benchmarks/RelayBenchmark/client.pfx -------------------------------------------------------------------------------- /Benchmarks/SecureProtobuffBenchmark/client.pfx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReferenceType/StandardNetworkLibrary/HEAD/Benchmarks/SecureProtobuffBenchmark/client.pfx -------------------------------------------------------------------------------- /Benchmarks/SecureProtobuffBenchmark/server.pfx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReferenceType/StandardNetworkLibrary/HEAD/Benchmarks/SecureProtobuffBenchmark/server.pfx -------------------------------------------------------------------------------- /NetworkLibrary/TCP/SSL/Certificates/client.pfx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReferenceType/StandardNetworkLibrary/HEAD/NetworkLibrary/TCP/SSL/Certificates/client.pfx -------------------------------------------------------------------------------- /NetworkLibrary/TCP/SSL/Certificates/server.pfx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReferenceType/StandardNetworkLibrary/HEAD/NetworkLibrary/TCP/SSL/Certificates/server.pfx -------------------------------------------------------------------------------- /Protobuff/Components/IProtoMessage.cs: -------------------------------------------------------------------------------- 1 | /// 2 | /// Represents a class which is serializable by protobuf.net 3 | /// 4 | public interface IProtoMessage { } 5 | 6 | -------------------------------------------------------------------------------- /SerializedNetwork/HybridProtoNetwork/HybridNetwork.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Json/Pure/JsonClient.cs: -------------------------------------------------------------------------------- 1 | using JsonNetwork.Components; 2 | using NetworkLibrary.TCP.Generic; 3 | 4 | namespace JsonNetwork.Pure 5 | { 6 | internal class JsonClient : GenericClient 7 | { 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Protobuff/Pure/PureProtoClient.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.TCP.Generic; 2 | using Protobuff.Components.Serialiser; 3 | 4 | namespace Protobuff.Pure 5 | { 6 | public class PureProtoClient : GenericClient 7 | { 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /SerializedNetwork/JsonNetwork/PureJsonClient.cs: -------------------------------------------------------------------------------- 1 | using JsonMessageNetwork.Components; 2 | using NetworkLibrary.TCP.Generic; 3 | 4 | namespace JsonMessageNetwork 5 | { 6 | public class PureJsonClient : GenericClient 7 | { 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /NetSerializer/Pure/NetSerialiserClient.cs: -------------------------------------------------------------------------------- 1 | using NetSerializerNetwork.Components; 2 | using NetworkLibrary.TCP.Generic; 3 | 4 | namespace NetSerializerNetwork.Pure 5 | { 6 | internal class NetSerialiserClient : GenericClient 7 | { 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /NetworkLibrary/MessageProtocol/Generic/Interfaces/IRouterHeader.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace NetworkLibrary.MessageProtocol 4 | { 5 | public interface IRouterHeader 6 | { 7 | bool IsInternal { get; set; } 8 | Guid To { get; set; } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Json/MessageProtocol/JsonMessageClient.cs: -------------------------------------------------------------------------------- 1 | using JsonNetwork.Components; 2 | using NetworkLibrary.MessageProtocol.Fast; 3 | 4 | namespace JsonNetwork.MessageProtocol 5 | { 6 | internal class JsonMessageClient : GenericMessageClientWrapper 7 | { 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Protobuff/Components/ConcurrentProtoSerializer.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.MessageProtocol; 2 | using Protobuff.Components.Serialiser; 3 | 4 | namespace Protobuff 5 | { 6 | public class ConcurrentProtoSerialiser : GenericMessageSerializer 7 | { } 8 | 9 | } 10 | 11 | -------------------------------------------------------------------------------- /SerializedNetwork/MessagePackNetwork/PureMessagePackClient.cs: -------------------------------------------------------------------------------- 1 | using MessagePackNetwork.Components; 2 | using NetworkLibrary.TCP.Generic; 3 | 4 | namespace MessagePackNetwork 5 | { 6 | public class PureMessagePackClient : GenericClient 7 | { 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /SerializedNetwork/BinarySerializerNetwork/PureBinaryClient.cs: -------------------------------------------------------------------------------- 1 | using BinarySerializerNetwork.Components; 2 | using NetworkLibrary.TCP.Generic; 3 | 4 | namespace BinarySerializerNetwork 5 | { 6 | public class PureBinaryClient : GenericClient 7 | { 8 | 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /NetworkLibrary/MessageProtocol/Serialization/RouterHeader.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace NetworkLibrary.MessageProtocol.Serialization 4 | { 5 | public ref struct RouterHeader 6 | { 7 | public bool IsInternal; 8 | public Guid To; 9 | } 10 | 11 | } 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /SerializedNetwork/DataContractNetwork/PureDataContractClient.cs: -------------------------------------------------------------------------------- 1 | using DataContractNetwork.Components; 2 | using NetworkLibrary.TCP.Generic; 3 | 4 | namespace DataContractNetwork 5 | { 6 | internal class PureDataContractClient : GenericClient 7 | { 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /NetworkLibrary/MessageProtocol/Fast/ISerialisableMessageQueue.cs: -------------------------------------------------------------------------------- 1 | namespace NetworkLibrary.MessageProtocol 2 | { 3 | internal interface ISerialisableMessageQueue 4 | { 5 | bool TryEnqueueMessage(MessageEnvelope envelope, T message); 6 | bool TryEnqueueMessage(MessageEnvelope envelope); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /NetSerializer/MessageProtocol/NetSerialiserMessageClient.cs: -------------------------------------------------------------------------------- 1 | using NetSerializerNetwork.Components; 2 | using NetworkLibrary.MessageProtocol.Fast; 3 | 4 | namespace NetSerializerNetwork.MessageProtocol 5 | { 6 | internal class NetSerialiserMessageClient : GenericMessageClientWrapper 7 | { 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /MessagePack/MessageProtocol/MessagePackMessageClient.cs: -------------------------------------------------------------------------------- 1 | using MessagePackNetwork.Components; 2 | using NetworkLibrary.MessageProtocol.Fast; 3 | 4 | namespace MessagePackNetwork.MessageProtocol 5 | { 6 | internal class MessagePackMessageClient:GenericMessageClientWrapper 7 | { 8 | 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /SerializedNetwork/CustomSerializer/CustomSerializer.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /SerializedNetwork/DataContractNetwork/DataContractNetwork.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /Json/Pure/JsonServer.cs: -------------------------------------------------------------------------------- 1 | using JsonNetwork.Components; 2 | using NetworkLibrary.TCP.Generic; 3 | 4 | namespace JsonNetwork.Pure 5 | { 6 | internal class JsonServer : GenericServer 7 | { 8 | public JsonServer(int port, bool writeLenghtPrefix = true) : base(port, writeLenghtPrefix) 9 | { 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /NetworkLibrary/Components/Crypto/Certificate/Native/KeyType.cs: -------------------------------------------------------------------------------- 1 | 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | 7 | namespace NetworkLibrary.Components.Crypto.Certificate.Native 8 | { 9 | public enum KeyType : int 10 | { 11 | Exchange = 1, 12 | Signature = 2, 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /SerializedNetwork/BinarySerializerNetwork/BinarySerializerNetwork.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /Json/MessageProtocol/JsonMessageServer.cs: -------------------------------------------------------------------------------- 1 | using JsonNetwork.Components; 2 | using NetworkLibrary.MessageProtocol.Fast; 3 | 4 | namespace JsonNetwork.MessageProtocol 5 | { 6 | internal class JsonMessageServer : GenericMessageServerWrapper 7 | { 8 | public JsonMessageServer(int port) : base(port) 9 | { 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Protobuff/Pure/PureProtoServer.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.TCP.Generic; 2 | using Protobuff.Components.Serialiser; 3 | 4 | namespace Protobuff.Pure 5 | { 6 | public class PureProtoServer : GenericServer 7 | { 8 | public PureProtoServer(int port, bool writeLenghtPrefix = true) : base(port, writeLenghtPrefix) 9 | { 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /SerializedNetwork/JsonNetwork/PureJsonServer.cs: -------------------------------------------------------------------------------- 1 | using JsonMessageNetwork.Components; 2 | using NetworkLibrary.TCP.Generic; 3 | 4 | namespace JsonMessageNetwork 5 | { 6 | public class PureJsonServer : GenericServer 7 | { 8 | public PureJsonServer(int port, bool writeLenghtPrefix = true) : base(port, writeLenghtPrefix) 9 | { 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /NetworkLibrary/MessageProtocol/Generic/Interfaces/ISerialisableMessageQueue.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.Components; 2 | 3 | namespace NetworkLibrary.MessageProtocol 4 | { 5 | public interface ISerialisableMessageQueue : IMessageQueue where U : IMessageEnvelope 6 | { 7 | bool TryEnqueueMessage(U envelope, T message); 8 | bool TryEnqueueMessage(U envelope); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Json/P2P/JsonRelayClient.cs: -------------------------------------------------------------------------------- 1 | using JsonNetwork.Components; 2 | using NetworkLibrary.P2P.Generic; 3 | using System.Security.Cryptography.X509Certificates; 4 | 5 | namespace JsonNetwork.P2P 6 | { 7 | internal class JsonRelayClient : RelayClientBase 8 | { 9 | public JsonRelayClient(X509Certificate2 clientCert) : base(clientCert) 10 | { 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /MessagePack/Pure/MessagePackClient.cs: -------------------------------------------------------------------------------- 1 | using MessagePackNetwork.Components; 2 | using NetworkLibrary.TCP.Generic; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace MessagePackNetwork.Pure 10 | { 11 | internal class MessagePackClient:GenericClient 12 | { 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /SerializedNetwork/Benchmarks/JsonMessageBenchmark/JsonMessageBenchmark.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /NetSerializer/Pure/NetSerialiserServer.cs: -------------------------------------------------------------------------------- 1 | using NetSerializerNetwork.Components; 2 | using NetworkLibrary.TCP.Generic; 3 | 4 | namespace NetSerializerNetwork.Pure 5 | { 6 | internal class NetSerialiserServer : GenericServer 7 | { 8 | public NetSerialiserServer(int port, bool writeLenghtPrefix = true) : base(port, writeLenghtPrefix) 9 | { 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Json/P2P/Room/JsonRoomClient.cs: -------------------------------------------------------------------------------- 1 | using JsonNetwork.Components; 2 | using NetworkLibrary.P2P.Generic.Room; 3 | using System.Security.Cryptography.X509Certificates; 4 | 5 | namespace JsonNetwork.P2P.Room 6 | { 7 | internal class JsonRoomClient : SecureLobbyClient 8 | { 9 | public JsonRoomClient(X509Certificate2 clientCert) : base(clientCert) 10 | { 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /NetworkLibrary/MessageProtocol/Generic/Interfaces/ISerializer.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | 3 | namespace NetworkLibrary.MessageProtocol 4 | { 5 | public interface ISerializer 6 | { 7 | void Serialize(Stream destination, T instance); 8 | byte[] Serialize(T instance); 9 | T Deserialize(Stream source); 10 | T Deserialize(byte[] buffer, int offset, int count); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /NetSerializer/MessageProtocol/NetSerialiserMessageServer.cs: -------------------------------------------------------------------------------- 1 | using NetSerializerNetwork.Components; 2 | using NetworkLibrary.MessageProtocol.Fast; 3 | 4 | namespace NetSerializerNetwork.MessageProtocol 5 | { 6 | internal class NetSerialiserMessageServer : GenericMessageServerWrapper 7 | { 8 | public NetSerialiserMessageServer(int port) : base(port) 9 | { 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /SerializedNetwork/Benchmarks/MessagepackBenchmark/MessagePackBenchmark.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /SerializedNetwork/BinarySerializerNetwork/PureBinaryServer.cs: -------------------------------------------------------------------------------- 1 | using BinarySerializerNetwork.Components; 2 | using NetworkLibrary.TCP.Generic; 3 | 4 | namespace BinarySerializerNetwork 5 | { 6 | internal class PureBinaryServer : GenericServer 7 | { 8 | public PureBinaryServer(int port, bool writeLenghtPrefix = true) : base(port, writeLenghtPrefix) 9 | { 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Protobuff/P2P/SecureLobbyClient.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.P2P.Generic.Room; 2 | using Protobuff.Components.Serialiser; 3 | using System.Security.Cryptography.X509Certificates; 4 | 5 | namespace Protobuff.P2P 6 | { 7 | public class SecureProtoRoomClient : SecureLobbyClient 8 | { 9 | public SecureProtoRoomClient(X509Certificate2 clientCert) : base(clientCert) 10 | { 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /SerializedNetwork/MessagePackNetwork/PureMessagePackServer.cs: -------------------------------------------------------------------------------- 1 | using MessagePackNetwork.Components; 2 | using NetworkLibrary.TCP.Generic; 3 | 4 | namespace MessagePackNetwork 5 | { 6 | internal class PureMessagePackServer : GenericServer 7 | { 8 | public PureMessagePackServer(int port, bool writeLenghtPrefix = true) : base(port, writeLenghtPrefix) 9 | { 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /SerializedNetwork/DataContractNetwork/PureDataContractServer.cs: -------------------------------------------------------------------------------- 1 | using DataContractNetwork.Components; 2 | using NetworkLibrary.TCP.Generic; 3 | 4 | namespace DataContractNetwork 5 | { 6 | internal class PureDataContractServer : GenericServer 7 | { 8 | public PureDataContractServer(int port, bool writeLenghtPrefix = true) : base(port, writeLenghtPrefix) 9 | { 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Benchmarks/RudpBenchmark/RudpBenchmark.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /SerializedNetwork/ProtobufNetwork/ProtobufNetwork.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /Benchmarks/HybridProtoNetworkBenchmark/ProtoNetworkBenchmark.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /NetSerializer/P2P/NetSerialiserRelayClient.cs: -------------------------------------------------------------------------------- 1 | using NetSerializerNetwork.Components; 2 | using NetworkLibrary.P2P.Generic; 3 | using System.Security.Cryptography.X509Certificates; 4 | 5 | namespace NetSerializerNetwork.P2P 6 | { 7 | internal class NetSerialiserRelayClient : RelayClientBase 8 | { 9 | public NetSerialiserRelayClient(X509Certificate2 clientCert) : base(clientCert) 10 | { 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /SerializedNetwork/JsonNetwork/JsonMessageNetwork.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /Json/Pure/SecureJsonClient.cs: -------------------------------------------------------------------------------- 1 | using JsonNetwork.Components; 2 | using NetworkLibrary.TCP.Generic; 3 | using System.Security.Cryptography.X509Certificates; 4 | 5 | namespace JsonNetwork.Pure 6 | { 7 | internal class SecureJsonClient : GenericSecureClient 8 | { 9 | public SecureJsonClient(X509Certificate2 certificate, bool writeLenghtPrefix = true) : base(certificate, writeLenghtPrefix) 10 | { 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /SerializedNetwork/NetSerializerNetwork/NetSerializerNetwork.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /NetSerializer/P2P/Room/NetSerialiserRoomClient.cs: -------------------------------------------------------------------------------- 1 | using NetSerializerNetwork.Components; 2 | using NetworkLibrary.P2P.Generic.Room; 3 | using System.Security.Cryptography.X509Certificates; 4 | 5 | namespace NetSerializerNetwork.P2P.Room 6 | { 7 | internal class NetSerialiserRoomClient : SecureLobbyClient 8 | { 9 | public NetSerialiserRoomClient(X509Certificate2 clientCert) : base(clientCert) 10 | { 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /SerializedNetwork/Benchmarks/ProtobuffBenchmark/ProtobuffBenchmark.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /Json/MessageProtocol/SecureJsonMessageClient.cs: -------------------------------------------------------------------------------- 1 | using JsonNetwork.Components; 2 | using NetworkLibrary.MessageProtocol.Fast; 3 | using System.Security.Cryptography.X509Certificates; 4 | 5 | namespace JsonNetwork.MessageProtocol 6 | { 7 | internal class SecureJsonMessageClient : GenericSecureMessageClientWrapper 8 | { 9 | public SecureJsonMessageClient(X509Certificate2 certificate) : base(certificate) 10 | { 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Json/Pure/SecureJsonServer.cs: -------------------------------------------------------------------------------- 1 | using JsonNetwork.Components; 2 | using NetworkLibrary.TCP.Generic; 3 | using System.Security.Cryptography.X509Certificates; 4 | 5 | namespace JsonNetwork.Pure 6 | { 7 | internal class SecureJsonServer : GenericSecureServer 8 | { 9 | public SecureJsonServer(int port, X509Certificate2 certificate, bool writeLenghtPrefix = true) : base(port, certificate, writeLenghtPrefix) 10 | { 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Benchmarks/TcpBenchmark/TcpMessageBenchmark.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | AnyCPU;ARM32 8 | False 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /Protobuff/Pure/PureSecureProtoClient.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.TCP.Generic; 2 | using Protobuff.Components.Serialiser; 3 | using System.Security.Cryptography.X509Certificates; 4 | 5 | namespace Protobuff.Pure 6 | { 7 | public class PureSecureProtoClient : GenericSecureClient 8 | { 9 | public PureSecureProtoClient(X509Certificate2 certificate, bool writeLenghtPrefix = true) : base(certificate, writeLenghtPrefix) 10 | { 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Json/MessageProtocol/SecureJsonMessageServer.cs: -------------------------------------------------------------------------------- 1 | using JsonNetwork.Components; 2 | using NetworkLibrary.MessageProtocol.Fast; 3 | using System.Security.Cryptography.X509Certificates; 4 | 5 | namespace JsonNetwork.MessageProtocol 6 | { 7 | internal class SecureJsonMessageServer : GenericSecureMessageServerWrapper 8 | { 9 | public SecureJsonMessageServer(int port, X509Certificate2 cerificate) : base(port, cerificate) 10 | { 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /SerializedNetwork/CustomSerializer/ServerClientSession.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.MessageProtocol; 2 | using System; 3 | using System.Net.Sockets; 4 | 5 | namespace CustomSerializer 6 | { 7 | public class CustomMessageClient : MessageClient 8 | { 9 | 10 | } 11 | 12 | public class CustomMessageServer : MessageServer 13 | { 14 | public CustomMessageServer(int port) : base(port) 15 | { 16 | } 17 | } 18 | 19 | 20 | } 21 | -------------------------------------------------------------------------------- /SerializedNetwork/Benchmarks/CustomSerializerBenchmark/CustomSerializerMessageBenchmark.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /SerializedNetwork/JsonNetwork/Internal/ClientServer.cs: -------------------------------------------------------------------------------- 1 | using JsonMessageNetwork.Components; 2 | using MessageProtocol; 3 | 4 | namespace JsonMessageNetwork.Internal 5 | { 6 | internal class ClientServer : MessageClient 7 | { 8 | } 9 | internal class JsonMessageServerInternal : MessageServer 10 | { 11 | public JsonMessageServerInternal(int port) : base(port) 12 | { 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /SerializedNetwork/Benchmarks/NetSerializerBenchmark/NetSerializerBenchmark.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /Protobuff/Pure/PureSecureProtoServer.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.TCP.Generic; 2 | using Protobuff.Components.Serialiser; 3 | using System.Security.Cryptography.X509Certificates; 4 | 5 | namespace Protobuff.Pure 6 | { 7 | public class PureSecureProtoServer : GenericSecureServer 8 | { 9 | public PureSecureProtoServer(int port, X509Certificate2 certificate, bool writeLenghtPrefix = true) : base(port, certificate, writeLenghtPrefix) 10 | { 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /SerializedNetwork/Benchmarks/BinaryMessageBenchmark/BinaryMessageBenchmark.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /NetworkLibrary/P2P/RoomServer.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.P2P.Components; 2 | using NetworkLibrary.P2P.Generic.Room; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Security.Cryptography.X509Certificates; 6 | using System.Text; 7 | 8 | namespace NetworkLibrary.P2P 9 | { 10 | public class RoomServer : SecureLobbyServer 11 | { 12 | public RoomServer(int port, X509Certificate2 cerificate) : base(port, cerificate) 13 | { 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /SerializedNetwork/Benchmarks/DataContractMessageBenchmark/DataContractMessageBenchmark.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /SerializedNetwork/MessagePackNetwork/MessagePackNetwork.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | True 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /NetSerializer/Pure/SecureNetSerialiserClient.cs: -------------------------------------------------------------------------------- 1 | using NetSerializerNetwork.Components; 2 | using NetworkLibrary.TCP.Generic; 3 | using System.Security.Cryptography.X509Certificates; 4 | 5 | namespace NetSerializerNetwork.Pure 6 | { 7 | internal class SecureNetSerialiserClient : GenericSecureClient 8 | { 9 | public SecureNetSerialiserClient(X509Certificate2 certificate, bool writeLenghtPrefix = true) : base(certificate, writeLenghtPrefix) 10 | { 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Protobuff/ProtoMessageClient.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary; 2 | using NetworkLibrary.Components.Statistics; 3 | using NetworkLibrary.MessageProtocol; 4 | using NetworkLibrary.MessageProtocol.Fast; 5 | using Protobuff.Components; 6 | using Protobuff.Components.Serialiser; 7 | using System; 8 | using System.Runtime.CompilerServices; 9 | using System.Threading.Tasks; 10 | 11 | namespace Protobuff 12 | { 13 | 14 | public class ProtoMessageClient:GenericMessageClientWrapper 15 | { 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Benchmarks/UdpBenchmark/UdpBenchmark.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Exe 6 | net7.0 7 | enable 8 | enable 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /NetSerializer/MessageProtocol/SecureNetSerialiserMessageClient.cs: -------------------------------------------------------------------------------- 1 | using NetSerializerNetwork.Components; 2 | using NetworkLibrary.MessageProtocol.Fast; 3 | using System.Security.Cryptography.X509Certificates; 4 | 5 | namespace NetSerializerNetwork.MessageProtocol 6 | { 7 | internal class SecureNetSerialiserMessageClient : GenericSecureMessageClientWrapper 8 | { 9 | public SecureNetSerialiserMessageClient(X509Certificate2 certificate) : base(certificate) 10 | { 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /NetSerializer/Pure/SecureNetSerialiserServer.cs: -------------------------------------------------------------------------------- 1 | using NetSerializerNetwork.Components; 2 | using NetworkLibrary.TCP.Generic; 3 | using System.Security.Cryptography.X509Certificates; 4 | 5 | namespace NetSerializerNetwork.Pure 6 | { 7 | internal class SecureNetSerialiserServer : GenericSecureServer 8 | { 9 | public SecureNetSerialiserServer(int port, X509Certificate2 certificate, bool writeLenghtPrefix = true) : base(port, certificate, writeLenghtPrefix) 10 | { 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /SerializedNetwork/ProtobufNetwork/InternalClientServerSessioncs.cs: -------------------------------------------------------------------------------- 1 | using MessageProtocol; 2 | using System; 3 | using System.Net.Sockets; 4 | 5 | namespace ProtobufNetwork 6 | { 7 | internal class ProtoClientInternal : 8 | MessageClient 9 | { 10 | 11 | } 12 | internal class ProtoServerInternal : MessageServer 13 | { 14 | internal ProtoServerInternal(int port) : base(port) 15 | { 16 | } 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /MessagePack/P2P/Room/MessagePackRoomClient.cs: -------------------------------------------------------------------------------- 1 | using MessagePackNetwork.Components; 2 | using NetworkLibrary.P2P.Generic.Room; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Security.Cryptography.X509Certificates; 6 | using System.Text; 7 | 8 | namespace MessagePackNetwork.P2P.Lobby 9 | { 10 | internal class MessagePackRoomClient : SecureLobbyClient 11 | { 12 | public MessagePackRoomClient(X509Certificate2 clientCert) : base(clientCert) 13 | { 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /NetSerializer/MessageProtocol/SecureNetSerialiserMessageServer.cs: -------------------------------------------------------------------------------- 1 | using NetSerializerNetwork.Components; 2 | using NetworkLibrary.MessageProtocol.Fast; 3 | using System.Security.Cryptography.X509Certificates; 4 | 5 | namespace NetSerializerNetwork.MessageProtocol 6 | { 7 | internal class SecureNetSerialiserMessageServer : GenericSecureMessageServerWrapper 8 | { 9 | public SecureNetSerialiserMessageServer(int port, X509Certificate2 cerificate) : base(port, cerificate) 10 | { 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /NetworkLibrary/Components/Crypto/Certificate/Native/KeyExchangeKey.cs: -------------------------------------------------------------------------------- 1 | 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | 7 | namespace NetworkLibrary.Components.Crypto.Certificate.Native 8 | { 9 | public class KeyExchangeKey : CryptKey 10 | { 11 | internal KeyExchangeKey(CryptContext ctx, IntPtr handle) : base(ctx, handle) {} 12 | 13 | public override KeyType Type 14 | { 15 | get { return KeyType.Exchange; } 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /MessagePack/P2P/MessagePackRelayClient.cs: -------------------------------------------------------------------------------- 1 | using MessagePack; 2 | using MessagePackNetwork.Components; 3 | using NetworkLibrary.P2P.Generic; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Security.Cryptography.X509Certificates; 7 | using System.Text; 8 | 9 | namespace MessagePackNetwork.P2P 10 | { 11 | internal class MessagePackRelayClient : RelayClientBase 12 | { 13 | public MessagePackRelayClient(X509Certificate2 clientCert) : base(clientCert) 14 | { 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /SerializedNetwork/MessagePackNetwork/Internal/ClientServer.cs: -------------------------------------------------------------------------------- 1 | using MessagePackNetwork.Components; 2 | using MessageProtocol; 3 | 4 | namespace MessagePackNetwork 5 | { 6 | internal class MessagePackMessageClientInternal : MessageClient 7 | { 8 | 9 | } 10 | internal class MessagePackMesssageServerInternal : MessageServer 11 | { 12 | public MessagePackMesssageServerInternal(int port) : base(port) 13 | { 14 | } 15 | 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /MessagePack/MessageProtocol/MessagePackMessageServer.cs: -------------------------------------------------------------------------------- 1 | using MessagePackNetwork.Components; 2 | using NetworkLibrary.MessageProtocol.Fast; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace MessagePackNetwork.MessageProtocol 10 | { 11 | internal class MessagePackMessageServer : GenericMessageServerWrapper 12 | { 13 | public MessagePackMessageServer(int port) : base(port) 14 | { 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /MessagePack/Pure/MessagePackServer.cs: -------------------------------------------------------------------------------- 1 | using MessagePack; 2 | using MessagePackNetwork.Components; 3 | using NetworkLibrary.TCP.Generic; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace MessagePackNetwork.Pure 11 | { 12 | internal class MessagePackServer : GenericServer 13 | { 14 | public MessagePackServer(int port, bool writeLenghtPrefix = true) : base(port, writeLenghtPrefix) 15 | { 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Protobuff/P2P/RelayClient.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.Components.Crypto; 2 | using NetworkLibrary.P2P.Generic; 3 | using Protobuff.Components.Serialiser; 4 | using System.Security.Cryptography.X509Certificates; 5 | 6 | 7 | namespace Protobuff.P2P 8 | { 9 | public class RelayClient : RelayClientBase 10 | { 11 | public RelayClient(X509Certificate2 clientCert, int udpPort = 0) : base(clientCert,udpPort) 12 | { 13 | } 14 | public RelayClient( int udpPort = 0) : base( udpPort) 15 | { 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /NetworkLibrary/P2P/Components/InfoMessages.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace NetworkLibrary.P2P.Components 5 | { 6 | public class PeerList 7 | { 8 | public Dictionary PeerIds { get; set; } 9 | } 10 | 11 | public class PeerInfo 12 | { 13 | public byte[] Address { get; set; } 14 | public ushort Port { get; set; } 15 | } 16 | 17 | public class RoomPeerList 18 | { 19 | public string RoomName { get; set; } 20 | public PeerList Peers; 21 | 22 | } 23 | 24 | 25 | } 26 | -------------------------------------------------------------------------------- /SerializedNetwork/NetSerializerNetwork/Internal/ServerClientSession.cs: -------------------------------------------------------------------------------- 1 | using MessageProtocol; 2 | using NetSerializerNetwork.Components; 3 | using System; 4 | using System.Net.Sockets; 5 | 6 | namespace NetSerializerNetwork.Internal 7 | { 8 | internal class NetSerializerClientInternal : MessageClient 9 | { 10 | } 11 | 12 | internal class NetSerializerServerIntenal : MessageServer 13 | { 14 | public NetSerializerServerIntenal(int port) : base(port) 15 | { 16 | } 17 | } 18 | 19 | 20 | } 21 | -------------------------------------------------------------------------------- /Tests/ConsoleTest/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /Protobuff/P2P/Generic/InfoMessages.cs: -------------------------------------------------------------------------------- 1 | using ProtoBuf; 2 | using System; 3 | using System.Collections.Generic; 4 | 5 | namespace Protobuff.P2P.Generic 6 | { 7 | public class PeerList : IProtoMessage 8 | { 9 | public Dictionary PeerIds { get; set; } 10 | } 11 | 12 | public class PeerInfo : IProtoMessage 13 | { 14 | public byte[] Address { get; set; } 15 | public ushort Port { get; set; } 16 | } 17 | 18 | public class RoomPeerList 19 | { 20 | public string RoomName { get; set; } 21 | public PeerList Peers; 22 | 23 | } 24 | 25 | 26 | } 27 | -------------------------------------------------------------------------------- /NetworkLibrary/P2P/RelayServer.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.MessageProtocol; 2 | using NetworkLibrary.P2P.Components; 3 | using NetworkLibrary.P2P.Generic; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.IO; 7 | using System.Security.Cryptography.X509Certificates; 8 | using System.Text; 9 | 10 | namespace NetworkLibrary.P2P 11 | { 12 | public class RelayServer : SecureRelayServerBase 13 | { 14 | public RelayServer(int port, X509Certificate2 certificate, string serverName = "Andromeda") : base(port, certificate, serverName) 15 | { 16 | } 17 | } 18 | 19 | 20 | } 21 | -------------------------------------------------------------------------------- /MessagePack/Pure/SecureMessagePackClient.cs: -------------------------------------------------------------------------------- 1 | using MessagePackNetwork.Components; 2 | using NetworkLibrary.TCP.Generic; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Security.Cryptography.X509Certificates; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace MessagePackNetwork.Pure 11 | { 12 | internal class SecureMessagePackClient : GenericSecureClient 13 | { 14 | public SecureMessagePackClient(X509Certificate2 certificate, bool writeLenghtPrefix = true) : base(certificate, writeLenghtPrefix) 15 | { 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /MessagePack/MessageProtocol/SecureMessagePackMessageClient.cs: -------------------------------------------------------------------------------- 1 | using MessagePackNetwork.Components; 2 | using NetworkLibrary.MessageProtocol.Fast; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Security.Cryptography.X509Certificates; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace MessagePackNetwork.MessageProtocol 11 | { 12 | internal class SecureMessagePackMessageClient : GenericSecureMessageClientWrapper 13 | { 14 | public SecureMessagePackMessageClient(X509Certificate2 certificate) : base(certificate) 15 | { 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /MessagePack/Pure/SecureMessagePackServer.cs: -------------------------------------------------------------------------------- 1 | using MessagePackNetwork.Components; 2 | using NetworkLibrary.TCP.Generic; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Security.Cryptography.X509Certificates; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace MessagePackNetwork.Pure 11 | { 12 | internal class SecureMessagePackServer : GenericSecureServer 13 | { 14 | public SecureMessagePackServer(int port, X509Certificate2 certificate, bool writeLenghtPrefix = true) : base(port, certificate, writeLenghtPrefix) 15 | { 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Protobuff/ProtoMessageServer.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary; 2 | using NetworkLibrary.Components.Statistics; 3 | using NetworkLibrary.MessageProtocol; 4 | using NetworkLibrary.MessageProtocol.Fast; 5 | using Protobuff.Components; 6 | using Protobuff.Components.Serialiser; 7 | using System; 8 | using System.Collections.Concurrent; 9 | using System.Net; 10 | using System.Runtime.CompilerServices; 11 | using System.Threading.Tasks; 12 | 13 | namespace Protobuff 14 | { 15 | public class ProtoMessageServer : GenericMessageServerWrapper 16 | { 17 | public ProtoMessageServer(int port) : base(port) 18 | { 19 | } 20 | } 21 | } 22 | 23 | -------------------------------------------------------------------------------- /Protobuff/P2P/SecureProtoRelayServer.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.P2P.Generic; 2 | using Protobuff.Components.Serialiser; 3 | using System.IO; 4 | using System; 5 | using System.Security.Cryptography.X509Certificates; 6 | using NetworkLibrary.MessageProtocol; 7 | using NetworkLibrary.P2P; 8 | 9 | namespace Protobuff.P2P 10 | { 11 | [Obsolete("SecureProtoRelayServer is obselete. Use NetworkLibrary.P2P.RelayServer")] 12 | public class SecureProtoRelayServer : SecureRelayServerBase 13 | { 14 | 15 | public SecureProtoRelayServer(int port, X509Certificate2 cerificate) : base(port, cerificate) 16 | { 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /MessagePack/MessageProtocol/SecureMessagePackMessageServer.cs: -------------------------------------------------------------------------------- 1 | using MessagePack; 2 | using MessagePackNetwork.Components; 3 | using NetworkLibrary.MessageProtocol.Fast; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Security.Cryptography.X509Certificates; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | 11 | namespace MessagePackNetwork.MessageProtocol 12 | { 13 | internal class SecureMessagePackMessageServer : GenericSecureMessageServerWrapper 14 | { 15 | public SecureMessagePackMessageServer(int port, X509Certificate2 cerificate) : base(port, cerificate) 16 | { 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /SerializedNetwork/BinarySerializerNetwork/Internal/ServerClientSession.cs: -------------------------------------------------------------------------------- 1 | using BinarySerializerNetwork.Components; 2 | using MessageProtocol; 3 | using System; 4 | using System.Net.Sockets; 5 | 6 | namespace BinarySerializerNetwork.Internal 7 | { 8 | internal class ServerClientSession 9 | { 10 | internal class NetSerializerClientInternal : MessageClient 11 | { 12 | } 13 | 14 | internal class NetSerializerServerIntenal : MessageServer 15 | { 16 | public NetSerializerServerIntenal(int port) : base(port) 17 | { 18 | } 19 | } 20 | 21 | 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /SerializedNetwork/DataContractNetwork/Internal/ServerClientSession.cs: -------------------------------------------------------------------------------- 1 | using DataContractNetwork.Components; 2 | using MessageProtocol; 3 | using System; 4 | using System.Net.Sockets; 5 | 6 | namespace DataContractNetwork.Internal 7 | { 8 | internal class ServerClientSession 9 | { 10 | internal class DataContractClientInternal : MessageClient 11 | { 12 | } 13 | 14 | internal class DataContractServerIntenal : MessageServer 15 | { 16 | public DataContractServerIntenal(int port) : base(port) 17 | { 18 | } 19 | } 20 | 21 | 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Benchmarks/RelayBenchmark/RelayBenchmark.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | PreserveNewest 17 | 18 | 19 | PreserveNewest 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /Protobuff/SecureProtoMessageClient.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary; 2 | using NetworkLibrary.Components; 3 | using NetworkLibrary.Components.Statistics; 4 | using NetworkLibrary.MessageProtocol.Fast; 5 | using Protobuff.Components; 6 | using Protobuff.Components.Serialiser; 7 | using System; 8 | using System.Net.Security; 9 | using System.Runtime.CompilerServices; 10 | using System.Security.Cryptography.X509Certificates; 11 | using System.Threading.Tasks; 12 | 13 | namespace Protobuff 14 | { 15 | public class SecureProtoMessageClient : GenericSecureMessageClientWrapper 16 | { 17 | public SecureProtoMessageClient(X509Certificate2 certificate) : base(certificate) 18 | { 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Tests/ConsoleTest/UnitTests/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | [assembly: AssemblyTitle("UnitTests")] 6 | [assembly: AssemblyDescription("")] 7 | [assembly: AssemblyConfiguration("")] 8 | [assembly: AssemblyCompany("")] 9 | [assembly: AssemblyProduct("UnitTests")] 10 | [assembly: AssemblyCopyright("Copyright © 2022")] 11 | [assembly: AssemblyTrademark("")] 12 | [assembly: AssemblyCulture("")] 13 | 14 | [assembly: ComVisible(false)] 15 | 16 | [assembly: Guid("d9a61287-1648-4412-b56d-4b3c972f225a")] 17 | 18 | // [assembly: AssemblyVersion("1.0.*")] 19 | [assembly: AssemblyVersion("1.0.0.0")] 20 | [assembly: AssemblyFileVersion("1.0.0.0")] 21 | -------------------------------------------------------------------------------- /Benchmarks/SslBenchmark/SslBenchmark.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | False 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | PreserveNewest 18 | 19 | 20 | PreserveNewest 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /Benchmarks/SslBenchmark2/SslBenchmark2.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | enable 7 | 8 | 9 | 10 | 11 | ..\..\NetworkLibrary\bin\Release\netstandard2.0\NetworkLibrary.dll 12 | 13 | 14 | 15 | 16 | 17 | PreserveNewest 18 | 19 | 20 | PreserveNewest 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /Examples/Examples.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | PreserveNewest 18 | 19 | 20 | PreserveNewest 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /NetworkLibrary/Utils/ConcurrentObjectPool.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | 3 | namespace NetworkLibrary.Utils 4 | { 5 | public class ConcurrentObjectPool where T : new() 6 | { 7 | public delegate T ConstructorCallback(); 8 | public ConstructorCallback HowToConstruct; 9 | 10 | public readonly ConcurrentBag pool = new ConcurrentBag(); 11 | 12 | public T RentObject() 13 | { 14 | if (!pool.TryTake(out T obj)) 15 | { 16 | return HowToConstruct == null ? new T() : HowToConstruct.Invoke(); 17 | } 18 | return obj; 19 | } 20 | 21 | public void ReturnObject(T obj) 22 | { 23 | pool.Add(obj); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Tests/ConsoleTest/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Protobuff/SecureProtoMessageServer.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary; 2 | using NetworkLibrary.Components; 3 | using NetworkLibrary.Components.Statistics; 4 | using NetworkLibrary.MessageProtocol.Fast; 5 | using Protobuff.Components; 6 | using Protobuff.Components.Serialiser; 7 | using System; 8 | using System.Collections.Concurrent; 9 | using System.Net; 10 | using System.Net.Security; 11 | using System.Runtime.CompilerServices; 12 | using System.Security.Cryptography.X509Certificates; 13 | using System.Threading.Tasks; 14 | 15 | namespace Protobuff 16 | { 17 | public class SecureProtoMessageServer : GenericSecureMessageServerWrapper 18 | { 19 | public SecureProtoMessageServer(int port, X509Certificate2 cerificate) : base(port, cerificate) 20 | { 21 | } 22 | } 23 | 24 | 25 | } 26 | -------------------------------------------------------------------------------- /SerializedNetwork/CustomSerializer/Serializer.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.MessageProtocol; 2 | using System; 3 | using System.IO; 4 | 5 | namespace CustomSerializer 6 | { 7 | public class Serializer_ : ISerializer 8 | { 9 | public T Deserialize(Stream source) 10 | { 11 | throw new NotImplementedException(); 12 | } 13 | 14 | public T Deserialize(byte[] buffer, int offset, int count) 15 | { 16 | throw new NotImplementedException(); 17 | } 18 | 19 | public void Serialize(Stream destination, T instance) 20 | { 21 | throw new NotImplementedException(); 22 | } 23 | 24 | public byte[] Serialize(T instance) 25 | { 26 | throw new NotImplementedException(); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /NetworkLibrary/Components/Crypto/Certificate/Native/Win32ErrorHelper.cs: -------------------------------------------------------------------------------- 1 | 2 | using System; 3 | using System.Runtime.InteropServices; 4 | 5 | namespace NetworkLibrary.Components.Crypto.Certificate.Native 6 | { 7 | internal static class Win32ErrorHelper 8 | { 9 | internal static void ThrowExceptionIfGetLastErrorIsNotZero() 10 | { 11 | int win32ErrorCode = Marshal.GetLastWin32Error(); 12 | if (0 != win32ErrorCode) 13 | Marshal.ThrowExceptionForHR(HResultFromWin32(win32ErrorCode)); 14 | } 15 | 16 | private static int HResultFromWin32(int win32ErrorCode) 17 | { 18 | if (win32ErrorCode > 0) 19 | return (int)((((uint)win32ErrorCode) & 0x0000FFFF) | 0x80070000U); 20 | else return win32ErrorCode; 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /NetworkLibrary/Components/Crypto/Certificate/Native/CryptKey.cs: -------------------------------------------------------------------------------- 1 | 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | 7 | namespace NetworkLibrary.Components.Crypto.Certificate.Native 8 | { 9 | public abstract class CryptKey : DisposeableObject 10 | { 11 | CryptContext ctx; 12 | IntPtr handle; 13 | 14 | internal IntPtr Handle { get { return handle; } } 15 | 16 | internal CryptKey(CryptContext ctx, IntPtr handle) 17 | { 18 | this.ctx = ctx; 19 | this.handle = handle; 20 | } 21 | 22 | public abstract KeyType Type { get; } 23 | 24 | protected override void CleanUp(bool viaDispose) 25 | { 26 | if (viaDispose) 27 | ctx.DestroyKey(this); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /NetworkLibrary/MessageProtocol/Generic/Interfaces/IMessageEnvelope.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace NetworkLibrary.MessageProtocol 5 | { 6 | public interface IMessageEnvelope 7 | { 8 | Guid From { get; set; } 9 | string Header { get; set; } 10 | bool IsLocked { get; } 11 | Dictionary KeyValuePairs { get; set; } 12 | Guid MessageId { get; set; } 13 | byte[] Payload { get; set; } 14 | int PayloadCount { get; } 15 | int PayloadOffset { get; } 16 | DateTime TimeStamp { get; set; } 17 | Guid To { get; set; } 18 | bool IsInternal { get; set; } 19 | 20 | void LockBytes(); 21 | void SetPayload(byte[] payloadBuffer, int offset, int count); 22 | T UnpackPayload(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /SerializedNetwork/HybridProtoNetwork/ServerClientSession.cs: -------------------------------------------------------------------------------- 1 | using MessageProtocol; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Net.Sockets; 5 | using System.Text; 6 | 7 | namespace CustomSerializer 8 | { 9 | public class CustomMessageClient : NetworkLibrary.MessageProtocol.Fast.MessageClient 10 | { 11 | 12 | } 13 | 14 | public class CustomMessageServer : NetworkLibrary.MessageProtocol.Fast.MessageServer 15 | { 16 | public CustomMessageServer(int port) : base(port) 17 | { 18 | } 19 | } 20 | 21 | public class CustomMessageSession : NetworkLibrary.MessageProtocol.Fast.MessageSession 22 | { 23 | public CustomMessageSession(SocketAsyncEventArgs acceptedArg, Guid sessionId) : base(acceptedArg, sessionId) 24 | { 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /SerializedNetwork/HybridProtoNetwork/Serializer.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.MessageProtocol; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Text; 6 | 7 | namespace CustomSerializer 8 | { 9 | public class Serializer_ : ISerializer 10 | { 11 | public T Deserialize(Stream source) 12 | { 13 | throw new NotImplementedException(); 14 | } 15 | 16 | public T Deserialize(byte[] buffer, int offset, int count) 17 | { 18 | throw new NotImplementedException(); 19 | } 20 | 21 | public void Serialize(Stream destination, T instance) 22 | { 23 | throw new NotImplementedException(); 24 | } 25 | 26 | public byte[] Serialize(T instance) 27 | { 28 | throw new NotImplementedException(); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /NetworkLibrary/P2P/Components/MockSerializer.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.MessageProtocol; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Text; 6 | 7 | namespace NetworkLibrary.P2P.Components 8 | { 9 | public class MockSerializer:ISerializer 10 | { 11 | public T Deserialize(Stream source) 12 | { 13 | throw new NotImplementedException(); 14 | } 15 | 16 | public T Deserialize(byte[] buffer, int offset, int count) 17 | { 18 | throw new NotImplementedException(); 19 | } 20 | 21 | public void Serialize(Stream destination, T instance) 22 | { 23 | throw new NotImplementedException(); 24 | } 25 | 26 | public byte[] Serialize(T instance) 27 | { 28 | throw new NotImplementedException(); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /NetworkLibrary/Utils/PrefixWriter.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | 3 | namespace NetworkLibrary.Utils 4 | { 5 | public class PrefixWriter 6 | { 7 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 8 | 9 | public static void WriteInt32AsBytes(ref byte[] buffer, int offset, int value) 10 | { 11 | buffer[0 + offset] = (byte)value; 12 | buffer[1 + offset] = (byte)(value >> 8); 13 | buffer[2 + offset] = (byte)(value >> 16); 14 | buffer[3 + offset] = (byte)(value >> 24); 15 | } 16 | 17 | public static void WriteInt32AsBytes(byte[] buffer, int offset, int value) 18 | { 19 | buffer[0 + offset] = (byte)value; 20 | buffer[1 + offset] = (byte)(value >> 8); 21 | buffer[2 + offset] = (byte)(value >> 16); 22 | buffer[3 + offset] = (byte)(value >> 24); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /NetworkLibrary/P2P/Components/HolePunch/Messages.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Net; 3 | 4 | namespace NetworkLibrary.P2P.Components.HolePunch 5 | { 6 | 7 | public class EndpointTransferMessage 8 | { 9 | public byte[] IpRemote { get; set; } 10 | public int PortRemote { get; set; } 11 | public List LocalEndpoints { get; set; } = new List(); 12 | } 13 | 14 | 15 | public class EndpointData 16 | { 17 | public byte[] Ip; 18 | public int Port; 19 | 20 | public IPEndPoint ToIpEndpoint() 21 | { 22 | return new IPEndPoint(new IPAddress(Ip), Port); 23 | } 24 | 25 | public EndpointData() 26 | { 27 | 28 | } 29 | 30 | public EndpointData(IPEndPoint ep) 31 | { 32 | Ip = ep.Address.GetAddressBytes(); 33 | Port = ep.Port; 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /NetworkLibrary/UDP/Reliable/Config/SenderModuleConfig.cs: -------------------------------------------------------------------------------- 1 | namespace NetworkLibrary.UDP.Reliable.Config 2 | { 3 | public class SenderModuleConfig 4 | { 5 | public int MaxSegmentSize = 64000; 6 | public int MaxRTO = 3000; 7 | public int RTOOffset = 20; 8 | public int MinRTO = 300; 9 | public int MaxWindowSize = 100_000_000; 10 | public int MinWindowSize = 64000; 11 | 12 | public bool EnableWindowBump = true; 13 | public int WindowBumpLowerTreshold = 50; 14 | public float WindowIncrementMultiplier = 1; 15 | 16 | public float TimeoutWindowTrim = 0.80f; 17 | public float SoftwindowTrim = 0.95f; 18 | public float PacingThreshold = 0.5f; 19 | 20 | } 21 | public class ReceiverModuleConfig 22 | { 23 | public bool EnableNacks = true; 24 | public bool EnablePEriodicSync = true; 25 | public int SyncTime = 200; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /NetworkLibrary/Components/Crypto/Certificate/Native/CertProperties.cs: -------------------------------------------------------------------------------- 1 | 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Security.Cryptography.X509Certificates; 7 | 8 | namespace NetworkLibrary.Components.Crypto.Certificate.Native 9 | { 10 | public class SelfSignedCertProperties 11 | { 12 | public DateTime ValidFrom { get; set; } 13 | public DateTime ValidTo { get; set; } 14 | public X500DistinguishedName Name { get; set; } 15 | public int KeyBitLength { get; set; } 16 | public bool IsPrivateKeyExportable { get; set; } 17 | 18 | public SelfSignedCertProperties() 19 | { 20 | DateTime today = DateTime.Today; 21 | ValidFrom = today.AddDays(-1); 22 | ValidTo = today.AddYears(10); 23 | Name = new X500DistinguishedName("cn=localhost"); 24 | KeyBitLength = 4096; 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Protobuff/P2P/Generic/HolePunch/Messages.cs: -------------------------------------------------------------------------------- 1 | using ProtoBuf; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Net; 5 | 6 | namespace Protobuff.P2P.Generic.HolePunch 7 | { 8 | 9 | internal class EndpointTransferMessage : IProtoMessage 10 | { 11 | public byte[] IpRemote { get; set; } 12 | public int PortRemote { get; set; } 13 | public List LocalEndpoints { get; set; } = new List(); 14 | } 15 | 16 | 17 | public class EndpointData 18 | { 19 | public byte[] Ip; 20 | public int Port; 21 | 22 | public IPEndPoint ToIpEndpoint() 23 | { 24 | return new IPEndPoint(new IPAddress(Ip), Port); 25 | } 26 | 27 | public EndpointData() 28 | { 29 | 30 | } 31 | 32 | public EndpointData(IPEndPoint ep) 33 | { 34 | Ip = ep.Address.GetAddressBytes(); 35 | Port = ep.Port; 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Benchmarks/SecureProtobuffBenchmark/ProtoSecureNetworkBenchmark.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | PreserveNewest 23 | 24 | 25 | PreserveNewest 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /NetworkLibrary/Components/Crypto/Algorithms/IAesAlgorithm.cs: -------------------------------------------------------------------------------- 1 | namespace NetworkLibrary.Components.Crypto.Algorithms 2 | { 3 | public interface IAesAlgorithm 4 | { 5 | int DecryptorInputBlockSize { get; } 6 | int DecryptorOutputBlockSize { get; } 7 | int EncryptorInputBlockSize { get; } 8 | int EncryptorOutputBlockSize { get; } 9 | 10 | byte[] Decrypt(byte[] message); 11 | byte[] Decrypt(byte[] buffer, int offset, int count); 12 | int DecryptInto(byte[] source, int sourceOffset, int sourceCount, byte[] output, int outputOffset); 13 | void Dispose(); 14 | byte[] Encrypt(byte[] message); 15 | byte[] Encrypt(byte[] buffer, int offset, int count); 16 | int EncryptInto(byte[] source, int sourceOffset, int sourceCount, byte[] output, int outputOffset); 17 | int EncryptInto(byte[] data1, int offset1, int count1, byte[] data2, int offset2, int count2, byte[] output, int outputOffset); 18 | int GetEncriptorOutputSize(int inputSize); 19 | 20 | } 21 | } -------------------------------------------------------------------------------- /NetworkLibrary/UDP/Reliable/Components/Segment.cs: -------------------------------------------------------------------------------- 1 | namespace NetworkLibrary.UDP.Reliable.Components 2 | { 3 | public readonly struct Segment 4 | { 5 | public readonly byte[] Array; 6 | public readonly int Offset; 7 | public readonly int Count; 8 | 9 | public Segment(byte[] array, int offset, int count) 10 | { 11 | Array = array; 12 | Offset = offset; 13 | Count = count; 14 | } 15 | public Segment(byte[] array) 16 | { 17 | Array = array; 18 | Offset = 0; 19 | Count = array.Length; 20 | } 21 | } 22 | internal readonly unsafe struct SegmentUnsafe 23 | { 24 | public readonly byte* Array; 25 | public readonly int Offset; 26 | public readonly int Count; 27 | 28 | public SegmentUnsafe(byte* array, int offset, int count) 29 | { 30 | Array = array; 31 | Offset = offset; 32 | Count = count; 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /SerializedNetwork/JsonNetwork/Components/JsonSerializer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | namespace JsonMessageNetwork.Components 4 | { 5 | public class JsonSerializer : NetworkLibrary.MessageProtocol.ISerializer 6 | { 7 | 8 | public T Deserialize(Stream source) 9 | { 10 | return System.Text.Json.JsonSerializer.Deserialize(source); 11 | } 12 | 13 | public T Deserialize(byte[] buffer, int offset, int count) 14 | { 15 | return System.Text.Json.JsonSerializer.Deserialize(new ReadOnlySpan(buffer, offset, count)); 16 | } 17 | 18 | public void Serialize(Stream destination, T instance) 19 | { 20 | System.Text.Json.JsonSerializer.Serialize(destination, instance); 21 | } 22 | 23 | public byte[] Serialize(T instance) 24 | { 25 | using (MemoryStream ms = new MemoryStream()) 26 | { 27 | System.Text.Json.JsonSerializer.Serialize(ms, instance); 28 | return ms.ToArray(); 29 | } 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /NetworkLibrary/MessageProtocol/Generic/Interfaces/IMessageSerialiser.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.Components; 2 | 3 | namespace NetworkLibrary.MessageProtocol 4 | { 5 | public interface IMessageSerialiser 6 | where E : IMessageEnvelope, new() 7 | { 8 | E DeserialiseEnvelopedMessage(byte[] buffer, int offset, int count); 9 | R DeserialiseOnlyRouterHeader(byte[] buffer, int offset, int count) where R : IRouterHeader, new(); 10 | T Deserialize(byte[] data, int offset, int count); 11 | byte[] EnvelopeMessageWithBytes(E empyEnvelope, byte[] payloadBuffer, int offset, int count); 12 | void EnvelopeMessageWithBytes(PooledMemoryStream serialisationStream, E empyEnvelope, byte[] payloadBuffer, int offset, int count); 13 | void EnvelopeMessageWithInnerMessage(PooledMemoryStream serialisationStream, E empyEnvelope, T payload); 14 | byte[] Serialize(T record); 15 | byte[] SerializeMessageEnvelope(E message); 16 | byte[] SerializeMessageEnvelope(E empyEnvelope, T payload); 17 | T UnpackEnvelopedMessage(E fullEnvelope); 18 | 19 | } 20 | } 21 | 22 | -------------------------------------------------------------------------------- /NetworkLibrary/TCP/SSL/ByteMessage/SsLByteMessageClient.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.TCP.Base; 2 | using NetworkLibrary.TCP.SSL.Base; 3 | using System; 4 | using System.Net; 5 | using System.Net.Security; 6 | using System.Security.Cryptography.X509Certificates; 7 | 8 | namespace NetworkLibrary.TCP.SSL.ByteMessage 9 | { 10 | public class SslByteMessageClient : SslClient 11 | { 12 | 13 | public SslByteMessageClient(X509Certificate2 certificate) : base(certificate) 14 | { 15 | } 16 | 17 | public SslByteMessageClient() : base() 18 | { 19 | } 20 | 21 | 22 | private protected override IAsyncSession CreateSession(Guid guid, ValueTuple tuple) 23 | { 24 | var ses = new SslByteMessageSession(guid, tuple.Item1); 25 | ses.MaxIndexedMemory = MaxIndexedMemory; 26 | ses.RemoteEndpoint = tuple.Item2; 27 | if (GatherConfig == ScatterGatherConfig.UseQueue) 28 | ses.UseQueue = true; 29 | else 30 | ses.UseQueue = false; 31 | 32 | return ses; 33 | } 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /NetworkLibrary/TCP/SSL/ByteMessage/SSlByteMessageServer.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.TCP.Base; 2 | using NetworkLibrary.TCP.SSL.Base; 3 | using System; 4 | using System.Net; 5 | using System.Net.Security; 6 | using System.Security.Cryptography.X509Certificates; 7 | 8 | namespace NetworkLibrary.TCP.SSL.ByteMessage 9 | { 10 | public class SslByteMessageServer : SslServer 11 | { 12 | public SslByteMessageServer(int port, X509Certificate2 certificate) : base(port, certificate) 13 | { 14 | } 15 | 16 | public SslByteMessageServer(int port) : base(port) 17 | { 18 | } 19 | 20 | private protected override IAsyncSession CreateSession(Guid guid, ValueTuple tuple) 21 | { 22 | var ses = new SslByteMessageSession(guid, tuple.Item1); 23 | ses.MaxIndexedMemory = MaxIndexedMemoryPerClient; 24 | ses.RemoteEndpoint = tuple.Item2; 25 | 26 | if (GatherConfig == ScatterGatherConfig.UseQueue) 27 | ses.UseQueue = true; 28 | else 29 | ses.UseQueue = false; 30 | 31 | return ses; 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /NetworkLibrary/P2P/Components/HolePunch/IPUtils.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Net; 4 | using System.Text; 5 | 6 | namespace NetworkLibrary 7 | { 8 | internal class IPUtils 9 | { 10 | //10.0.0.0 - 10.255.255.255 11 | //172.16.0.0 - 172.31.255.255 12 | //192.168.0.0 - 192.168.255.255 13 | public static bool IsPrivate(byte[] ipBytes) 14 | { 15 | if (ipBytes[0]== 192 && ipBytes[1] == 168) 16 | { 17 | return true; 18 | } 19 | else if (ipBytes[0] == 10) 20 | { 21 | return true; 22 | } 23 | else if (ipBytes[0] ==172 && (ipBytes[1]>15 && ipBytes[1] < 31)) 24 | { 25 | return true; 26 | } 27 | else { return false;} 28 | } 29 | 30 | public static bool IsLoopback(byte[] ipBtyes) 31 | { 32 | var addr = new IPAddress(ipBtyes); 33 | if (IPAddress.IsLoopback(addr)) 34 | { 35 | return true; 36 | } 37 | return false; 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Tests/UnitTests/EncryptionTest.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using NetworkLibrary.Components; 3 | using NuGet.Frameworks; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace UnitTests 11 | { 12 | [TestClass] 13 | public class EncryptionTest 14 | { 15 | [TestMethod] 16 | public void EncryptTest() 17 | { 18 | var key = new byte[16] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; 19 | var iv = new byte[16] { 21, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; 20 | ConcurrentAesAlgorithm alg = new ConcurrentAesAlgorithm(key); 21 | 22 | byte[] data = new byte[100]; 23 | data[1] = 99; 24 | byte[] out1 = new byte[150]; 25 | byte[] out2 = new byte[150]; 26 | 27 | int am=alg.EncryptInto(data,0,data.Length,out1,0); 28 | int dec=alg.DecryptInto(out1, 0, am, out2, 0); 29 | 30 | Assert.AreEqual(out2[1], data[1]); 31 | Assert.AreEqual(dec,data.Length); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Json/Components/JsonSerializer.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Threading; 6 | 7 | namespace JsonNetwork.Components 8 | { 9 | public class JsonSerializer : NetworkLibrary.MessageProtocol.ISerializer 10 | { 11 | 12 | public T Deserialize(Stream source) 13 | { 14 | return System.Text.Json.JsonSerializer.Deserialize(source); 15 | } 16 | 17 | public T Deserialize(byte[] buffer, int offset, int count) 18 | { 19 | return System.Text.Json.JsonSerializer.Deserialize(new ReadOnlySpan(buffer, offset, count)); 20 | } 21 | 22 | public void Serialize(Stream destination, T instance) 23 | { 24 | System.Text.Json.JsonSerializer.Serialize(destination, instance); 25 | } 26 | 27 | public byte[] Serialize(T instance) 28 | { 29 | using (MemoryStream ms = new MemoryStream()) 30 | { 31 | System.Text.Json.JsonSerializer.Serialize(ms, instance); 32 | return ms.ToArray(); 33 | } 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /NetworkLibrary/MessageProtocol/Fast/IMessageSerializer.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.Components; 2 | using NetworkLibrary.MessageProtocol.Serialization; 3 | 4 | namespace NetworkLibrary.MessageProtocol 5 | { 6 | public interface IMessageSerialiser 7 | { 8 | MessageEnvelope DeserialiseEnvelopedMessage(byte[] buffer, int offset, int count); 9 | RouterHeader DeserialiseOnlyRouterHeader(byte[] buffer, int offset, int count); 10 | T Deserialize(byte[] data, int offset, int count); 11 | byte[] EnvelopeMessageWithBytes(MessageEnvelope empyEnvelope, byte[] payloadBuffer, int offset, int count); 12 | void EnvelopeMessageWithBytes(PooledMemoryStream serialisationStream, MessageEnvelope empyEnvelope, byte[] payloadBuffer, int offset, int count); 13 | void EnvelopeMessageWithInnerMessage(PooledMemoryStream serialisationStream, MessageEnvelope empyEnvelope, T payload); 14 | byte[] Serialize(T record); 15 | byte[] SerializeMessageEnvelope(MessageEnvelope message); 16 | byte[] SerializeMessageEnvelope(MessageEnvelope empyEnvelope, T payload); 17 | T UnpackEnvelopedMessage(MessageEnvelope fullEnvelope); 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /NetworkLibrary/Components/Statistics/TcpClientStatisticsPublisher.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.TCP.Base; 2 | using System; 3 | using System.Collections.Concurrent; 4 | using System.Diagnostics; 5 | 6 | namespace NetworkLibrary.Components.Statistics 7 | { 8 | internal class TcpClientStatisticsPublisher 9 | { 10 | internal ConcurrentDictionary Stats { get; } = new ConcurrentDictionary(); 11 | internal readonly IAsyncSession Session; 12 | private TcpStatistics generalStats = new TcpStatistics(); 13 | private Stopwatch sw = new Stopwatch(); 14 | public TcpClientStatisticsPublisher(IAsyncSession session, in Guid sessionId) 15 | { 16 | Session = session; 17 | sw.Start(); 18 | } 19 | 20 | private void GetSessionStats() 21 | { 22 | var stats = Session.GetSessionStatistics(); 23 | generalStats.Update(stats, sw.ElapsedMilliseconds); 24 | 25 | } 26 | 27 | internal void GetStatistics(out TcpStatistics generalStats) 28 | { 29 | GetSessionStats(); 30 | generalStats = this.generalStats; 31 | } 32 | 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /NetworkLibrary/TCP/ByteMessage/ByteMessageTcpClient.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.TCP.Base; 2 | using System; 3 | using System.Net.Sockets; 4 | 5 | namespace NetworkLibrary.TCP.ByteMessage 6 | { 7 | /// 8 | /// Sends and reveives messages with 4 byte lenght header. 9 | /// messages are guarantied to be received atomically without fragmentation. 10 | /// 11 | public class ByteMessageTcpClient : AsyncTpcClient 12 | { 13 | 14 | public ByteMessageTcpClient() 15 | { } 16 | 17 | private protected override IAsyncSession CreateSession(SocketAsyncEventArgs e, Guid sessionId) 18 | { 19 | var session = new ByteMessageSession(e, sessionId); 20 | session.socketSendBufferSize = SocketSendBufferSize; 21 | session.SocketRecieveBufferSize = SocketRecieveBufferSize; 22 | session.MaxIndexedMemory = MaxIndexedMemory; 23 | session.DropOnCongestion = DropOnCongestion; 24 | 25 | if (GatherConfig == ScatterGatherConfig.UseQueue) 26 | session.UseQueue = true; 27 | else 28 | session.UseQueue = false; 29 | 30 | return session; 31 | 32 | } 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Tests/UnitTests/UnitTests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | 7 | false 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | PreserveNewest 27 | 28 | 29 | PreserveNewest 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /NetworkLibrary/TCP/ByteMessage/ByteMessageTcpServer.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.TCP.Base; 2 | using System; 3 | using System.Net.Sockets; 4 | 5 | namespace NetworkLibrary.TCP.ByteMessage 6 | { 7 | /// 8 | /// Sends and receives messages with 4 byte lenght header. 9 | /// Messages are guarantied to be received atomically without fragmentation. 10 | /// 11 | public class ByteMessageTcpServer : AsyncTcpServer 12 | { 13 | public ByteMessageTcpServer(int port) : base(port) 14 | { } 15 | 16 | private protected override IAsyncSession CreateSession(SocketAsyncEventArgs e, Guid sessionId) 17 | { 18 | var session = new ByteMessageSession(e, sessionId); 19 | session.socketSendBufferSize = ClientSendBufsize; 20 | session.SocketRecieveBufferSize = ClientReceiveBufsize; 21 | session.MaxIndexedMemory = MaxIndexedMemoryPerClient; 22 | session.DropOnCongestion = DropOnBackPressure; 23 | //session.OnSessionClosed += (id) => OnClientDisconnected?.Invoke(id); 24 | 25 | 26 | if (GatherConfig == ScatterGatherConfig.UseQueue) 27 | session.UseQueue = true; 28 | else 29 | session.UseQueue = false; 30 | 31 | return session; 32 | 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /NetSerializer/NetSerializerNetwork.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0;netstandard2.1;net5.0;net6.0;net7.0;net8.0 5 | True 6 | NetSerializer.Network.Library 7 | NetSerializer Network Library 8 | 2.0.0 9 | Message passing and P2P network library using .NetSerializer 10 | Apache-2.0 11 | https://github.com/ReferenceType/StandardNetworkLibrary 12 | netserializer;network;p2p;holepunch;nat traversal;high performance;reliable udp 13 | Licence.txt 14 | ReferenceType 15 | 16 | 17 | 18 | 19 | 20 | True 21 | \ 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /Json/JsonNetwork.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0;netstandard2.1;net5.0;net6.0;net7.0;net8.0 5 | True 6 | Json.Network.Library 7 | Json Network Library 8 | 2.0.0 9 | ReferenceType 10 | Message passing and P2P network library using System.Text.Json 11 | Apache-2.0 12 | https://github.com/ReferenceType/StandardNetworkLibrary 13 | json;network;p2p;holepunch;nat traversal;high performance;reliable udp 14 | Licence.txt 15 | For release notes, check https://github.com/ReferenceType/StandardNetworkLibrary 16 | 17 | 18 | 19 | 20 | True 21 | \ 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /NetworkLibrary/UDP/Jumbo/Mock.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.UDP.Reliable.Components; 2 | using System; 3 | 4 | namespace NetworkLibrary.UDP.Jumbo 5 | { 6 | public class Mock 7 | { 8 | JumboModule J1 = new JumboModule(); 9 | JumboModule J2 = new JumboModule(); 10 | public Action J1Received; 11 | public Action J2Received; 12 | public Mock() 13 | { 14 | J1.SendToSocket = J1Send; 15 | J2.SendToSocket = J2Send; 16 | J1.MessageReceived += (b, o, c) => J1Received?.Invoke(b, o, c); 17 | J2.MessageReceived += (b, o, c) => J2Received?.Invoke(b, o, c); 18 | } 19 | 20 | private void J2Send(byte[] arg1, int arg2, int arg3) 21 | { 22 | J1.HandleReceivedSegment(arg1, arg2, arg3); 23 | } 24 | 25 | private void J1Send(byte[] arg1, int arg2, int arg3) 26 | { 27 | J2.HandleReceivedSegment(arg1, arg2, arg3); 28 | } 29 | 30 | public void SendAsJ1(byte[] arg1, int arg2, int arg3) 31 | { 32 | J1.Send(arg1, arg2, arg3); 33 | } 34 | public void SendAsJ1(Segment s1, Segment s2) 35 | { 36 | J1.Send(s1,s2); 37 | } 38 | public void SendAsJ2(byte[] arg1, int arg2, int arg3) 39 | { 40 | J2.Send(arg1, arg2, arg3); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /NetworkLibrary/Utils/MiniLogger.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace NetworkLibrary.Utils 4 | { 5 | public class MiniLogger 6 | { 7 | public enum LogLevel { Debug, Info, Warning, Error }; 8 | public static event Action LogDebug; 9 | public static event Action LogInfo; 10 | public static event Action LogWarn; 11 | public static event Action LogError; 12 | public static event Action AllLog; 13 | 14 | public static void Log(LogLevel level, string message) 15 | { 16 | switch (level) 17 | { 18 | case LogLevel.Debug: 19 | LogDebug?.Invoke(message); 20 | AllLog?.Invoke("[Debug] " + message); 21 | break; 22 | case LogLevel.Info: 23 | LogInfo?.Invoke(message); 24 | AllLog?.Invoke("[Info] " + message); 25 | 26 | break; 27 | case LogLevel.Warning: 28 | LogWarn?.Invoke(message); 29 | AllLog?.Invoke("[Warning] " + message); 30 | 31 | break; 32 | case LogLevel.Error: 33 | LogError?.Invoke(message); 34 | AllLog?.Invoke("[Error] " + message); 35 | 36 | break; 37 | } 38 | 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /NetworkLibrary/TCP/SSL/ByteMessage/SSLByteMessageSession.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.Components; 2 | using NetworkLibrary.Components.MessageBuffer; 3 | using NetworkLibrary.Components.MessageProcessor.Unmanaged; 4 | using NetworkLibrary.TCP.SSL.Base; 5 | using System; 6 | using System.Net.Security; 7 | 8 | namespace NetworkLibrary.TCP.SSL.ByteMessage 9 | { 10 | internal class SslByteMessageSession : SslSession 11 | { 12 | ByteMessageReader reader; 13 | 14 | public SslByteMessageSession(Guid sessionId, SslStream sessionStream) : base(sessionId, sessionStream) 15 | { 16 | reader = new ByteMessageReader(); 17 | reader.OnMessageReady += HandleMessage; 18 | } 19 | 20 | private void HandleMessage(byte[] arg1, int arg2, int arg3) 21 | { 22 | base.HandleReceived(arg1, arg2, arg3); 23 | } 24 | protected override void HandleReceived(byte[] buffer, int offset, int count) 25 | { 26 | reader.ParseBytes(buffer, offset, count); 27 | } 28 | 29 | protected override IMessageQueue CreateMessageQueue() 30 | { 31 | if (UseQueue) 32 | return new MessageQueue(MaxIndexedMemory, new DelimitedMessageWriter()); 33 | 34 | else 35 | return new MessageBuffer(MaxIndexedMemory, writeLengthPrefix: true); 36 | } 37 | 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Protobuff/P2P/Generic/Constants.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary; 2 | using NetworkLibrary.MessageProtocol.Serialization; 3 | using ProtoBuf; 4 | 5 | namespace Protobuff.P2P.Generic 6 | { 7 | 8 | public class Constants 9 | { 10 | public const string Register = "1"; 11 | public const string ServerRegisterAck = "2"; 12 | public const string UdpInit = "3"; 13 | public const string ServerFinalizationCmd = "4"; 14 | public const string ClientFinalizationAck = "5"; 15 | public const string NotifyPeerListUpdate = "6"; 16 | 17 | //hp 18 | public const string InitiateHolepunch = "7"; 19 | public const string HolePunchSucces = "8"; 20 | public const string KeyTransfer = "9"; 21 | public const string HolpunchMessagesSent = "10"; 22 | public const string NotifyServerHolepunch = "11"; 23 | 24 | public const string Ping = "Ping"; 25 | public const string Pong = "Pong"; 26 | 27 | 28 | public const string RoomUpdate = "12"; 29 | public const string JoinRoom = "13"; 30 | public const string LeaveRoom = "14"; 31 | public const string GetAvailableRooms = "15"; 32 | public const string PeerDisconnected = "16"; 33 | public const string Rudp = "17"; 34 | public const string Rudp1 = "18"; 35 | public const string Judp = "19"; 36 | 37 | public const string RoomName = "42"; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /MessagePack/MessagePackNetwork.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0;netstandard2.1;net5.0;net6.0;net7.0;net8.0 5 | True 6 | MessagePack.Network.Library 7 | MessagePack Network Library 8 | 2.0.0 9 | ReferenceType 10 | Message passing and P2P network library using MessagePack Serialization 11 | Apache-2.0 12 | https://github.com/ReferenceType/StandardNetworkLibrary 13 | messagepack;network;p2p;holepunch;nat traversal;high performance;reliable udp 14 | Licence.txt 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | True 25 | \ 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /NetworkLibrary/Utils/Spinlock.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | using System.Threading; 3 | 4 | namespace NetworkLibrary.Utils 5 | { 6 | public class Spinlock 7 | { 8 | private int lockValue = 0; 9 | SpinWait spinWait = new SpinWait(); 10 | 11 | 12 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 13 | public void Take() 14 | { 15 | if (Interlocked.CompareExchange(ref lockValue, 1, 0) != 0) 16 | { 17 | int spinCount = 0; 18 | 19 | while (Interlocked.CompareExchange(ref lockValue, 1, 0) != 0) 20 | { 21 | 22 | if (spinCount < 22) 23 | { 24 | spinCount++; 25 | } 26 | 27 | else 28 | { 29 | spinWait.SpinOnce(); 30 | } 31 | } 32 | } 33 | 34 | } 35 | 36 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 37 | public bool IsTaken() => Interlocked.CompareExchange(ref lockValue, 1, 1) == 1; 38 | 39 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 40 | public void Release() 41 | { 42 | Interlocked.Exchange(ref lockValue, 0); 43 | } 44 | 45 | internal bool TryTake() 46 | { 47 | return Interlocked.CompareExchange(ref lockValue, 1, 0) == 0; 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /NetworkLibrary/Components/Crypto/Certificate/Native/DisposableObject.cs: -------------------------------------------------------------------------------- 1 | 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Runtime.InteropServices; 7 | 8 | namespace NetworkLibrary.Components.Crypto.Certificate.Native 9 | { 10 | [StructLayout(LayoutKind.Sequential)] 11 | public abstract class DisposeableObject : IDisposable 12 | { 13 | private bool disposed = false; 14 | 15 | ~DisposeableObject() 16 | { 17 | CleanUp(false); 18 | } 19 | 20 | public void Dispose() 21 | { 22 | // note this method does not throw ObjectDisposedException 23 | if (!disposed) 24 | { 25 | CleanUp(true); 26 | 27 | disposed = true; 28 | 29 | GC.SuppressFinalize(this); 30 | } 31 | } 32 | 33 | protected abstract void CleanUp(bool viaDispose); 34 | 35 | /// 36 | /// Typical check for derived classes 37 | /// 38 | protected void ThrowIfDisposed() 39 | { 40 | ThrowIfDisposed(this.GetType().FullName); 41 | } 42 | 43 | /// 44 | /// Typical check for derived classes 45 | /// 46 | protected void ThrowIfDisposed(string objectName) 47 | { 48 | if (disposed) 49 | throw new ObjectDisposedException(objectName); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /NetworkLibrary/Components/MessageBuffer/Interface/IMessageProcessQueue.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace NetworkLibrary.Components 4 | { 5 | public interface IMessageQueue : IDisposable 6 | { 7 | /// 8 | /// Enqueues the message if there is enough space available 9 | /// 10 | /// 11 | /// true if message is enqueued. 12 | bool TryEnqueueMessage(byte[] bytes); 13 | 14 | /// 15 | /// Enqueues the message if there is enough space available 16 | /// 17 | /// 18 | /// true if message is enqueued. 19 | bool TryEnqueueMessage(byte[] bytes, int offset, int count); 20 | 21 | /// 22 | /// Flushes the queue if there is anything to flush. 23 | /// 24 | /// 25 | /// 26 | /// 27 | /// true if something succesfully flushed. 28 | bool TryFlushQueue(ref byte[] buffer, int offset, out int amountWritten); 29 | 30 | /// 31 | /// Is Queue empty 32 | /// 33 | /// 34 | bool IsEmpty(); 35 | 36 | void Flush(); 37 | 38 | int CurrentIndexedMemory { get; } 39 | long TotalMessageDispatched { get; } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Tests/ConsoleTest/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // General Information about an assembly is controlled through the following 5 | // set of attributes. Change these attribute values to modify the information 6 | // associated with an assembly. 7 | [assembly: AssemblyTitle("ConsoleTest")] 8 | [assembly: AssemblyDescription("")] 9 | [assembly: AssemblyConfiguration("")] 10 | [assembly: AssemblyCompany("")] 11 | [assembly: AssemblyProduct("ConsoleTest")] 12 | [assembly: AssemblyCopyright("Copyright © 2022")] 13 | [assembly: AssemblyTrademark("")] 14 | [assembly: AssemblyCulture("")] 15 | 16 | // Setting ComVisible to false makes the types in this assembly not visible 17 | // to COM components. If you need to access a type in this assembly from 18 | // COM, set the ComVisible attribute to true on that type. 19 | [assembly: ComVisible(false)] 20 | 21 | // The following GUID is for the ID of the typelib if this project is exposed to COM 22 | [assembly: Guid("f8c710ab-feba-4f74-9e76-2dbdb15dea67")] 23 | 24 | // Version information for an assembly consists of the following four values: 25 | // 26 | // Major Version 27 | // Minor Version 28 | // Build Number 29 | // Revision 30 | // 31 | // You can specify all the values or you can default the Build and Revision Numbers 32 | // by using the '*' as shown below: 33 | // [assembly: AssemblyVersion("1.0.*")] 34 | [assembly: AssemblyVersion("1.0.0.0")] 35 | [assembly: AssemblyFileVersion("1.0.0.0")] 36 | -------------------------------------------------------------------------------- /SerializedNetwork/MessagePackNetwork/Components/MessagePackSerializer.cs: -------------------------------------------------------------------------------- 1 | using MessagePack; 2 | using NetworkLibrary.Components; 3 | using System; 4 | using System.Buffers; 5 | using System.IO; 6 | 7 | namespace MessagePackNetwork.Components 8 | { 9 | public class MessagepackSerializer : NetworkLibrary.MessageProtocol.ISerializer 10 | { 11 | [ThreadStatic] 12 | BufferWriter wrt = new BufferWriter(); 13 | 14 | public MessagepackSerializer() 15 | { 16 | 17 | } 18 | 19 | public T Deserialize(Stream source) 20 | { 21 | var buff = ((PooledMemoryStream)source).GetBuffer(); 22 | return MessagePackSerializer.Deserialize(new ReadOnlyMemory(buff, 0, (int)source.Position)); 23 | } 24 | 25 | public T Deserialize(byte[] buffer, int offset, int count) 26 | { 27 | return MessagePackSerializer.Deserialize(new ReadOnlyMemory(buffer, offset, count)); 28 | } 29 | 30 | public void Serialize(Stream destination, T instance) 31 | { 32 | //wrt.SetStream((PooledMemoryStream)destination); 33 | var wrt = new BufferWriter((PooledMemoryStream)destination); 34 | //byte[] bytes = MessagePackSerializer.Serialize(instance); 35 | //destination.Write(bytes, 0, bytes.Length); 36 | 37 | MessagePackSerializer.Serialize(wrt, instance); 38 | } 39 | 40 | public byte[] Serialize(T instance) 41 | { 42 | return MessagePackSerializer.Serialize(instance); 43 | } 44 | } 45 | 46 | } 47 | 48 | -------------------------------------------------------------------------------- /NetworkLibrary/Components/MessageProcessor/Interface/IMessageProcessor.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace NetworkLibrary.Components 4 | { 5 | public interface IMessageProcessor : IDisposable 6 | { 7 | // heldover 8 | 9 | /// 10 | /// Sets a buffer where the messages will be proccessed into 11 | /// 12 | /// 13 | /// 14 | void SetBuffer(ref byte[] buffer, int offset); 15 | 16 | /// 17 | /// Proccesses a given message into a buffer set by 18 | /// 19 | /// 20 | /// true if message is completely process, false means message is partially processed and its heldover, 21 | /// indicates flush is required returns> 22 | bool ProcessMessage(byte[] message); 23 | 24 | /// 25 | /// Flushes a heldover message into buffer set by . 26 | /// 27 | /// true if heldover message is completel flushed, false if the messages isnt fully processed. 28 | bool Flush(); 29 | 30 | /// 31 | /// Returns the buffer set by 32 | /// 33 | /// 34 | /// 35 | /// 36 | void GetBuffer(out byte[] Buffer, out int offset, out int count); 37 | 38 | 39 | bool IsHoldingMessage { get; } 40 | 41 | } 42 | } -------------------------------------------------------------------------------- /NetworkLibrary/UDP/Reliable/Helpers/Compactor.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.Components; 2 | using System; 3 | 4 | namespace NetworkLibrary.UDP.Reliable.Helpers 5 | { 6 | class Compactor 7 | { 8 | PooledMemoryStream prev; 9 | PooledMemoryStream stream = new PooledMemoryStream(); 10 | public Action OnOut; 11 | int remaining = 64000; 12 | public void Push(PooledMemoryStream curr) 13 | { 14 | if (curr.Position32 >= 64000) 15 | { 16 | Flush(); 17 | prev = curr; 18 | Flush(); 19 | } 20 | else if (prev == null) 21 | { 22 | prev = curr; 23 | } 24 | else if (curr.Position32 + prev.Position32 < remaining) 25 | { 26 | stream.Write(prev.GetBuffer(), 0, (int)prev.Position32); 27 | remaining -= (int)prev.Position32; 28 | prev = curr; 29 | } 30 | else 31 | { 32 | Flush(); 33 | prev = curr; 34 | Flush(); 35 | } 36 | } 37 | 38 | public void Flush() 39 | { 40 | if (stream.Position32 > 0) 41 | { 42 | OnOut(stream.GetBuffer(), 0, stream.Position32); 43 | stream.Position32 = 0; 44 | remaining = 64000; 45 | } 46 | if (prev != null) 47 | { 48 | OnOut(prev.GetBuffer(), 0, prev.Position32); 49 | prev = null; 50 | } 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Tests/UnitTests/MessageTests.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using NetworkLibrary.Components; 3 | using NetworkLibrary.Utils; 4 | using System; 5 | using System.Diagnostics; 6 | 7 | namespace UnitTests 8 | { 9 | [TestClass] 10 | public class MessageTests 11 | { 12 | 13 | [TestMethod] 14 | public void TestMessageParser() 15 | { 16 | Stopwatch sw = new Stopwatch(); 17 | int NumMsg = 0; 18 | ByteMessageReader msgMan = new ByteMessageReader( 128000); 19 | msgMan.OnMessageReady += (byte[] msg, int off, int ct) => NumMsg++; 20 | 21 | byte[] data = new byte[108]; 22 | PrefixWriter.WriteInt32AsBytes(data, 0, 32); 23 | PrefixWriter.WriteInt32AsBytes(data, 36, 32); 24 | PrefixWriter.WriteInt32AsBytes(data, 72, 32); 25 | 26 | byte[][] data1 = new byte[108][]; 27 | for (int j = 0; j < 108; j++) 28 | { 29 | data1[j] = new byte[1] { data[j] }; 30 | } 31 | 32 | 33 | int cut = 22; 34 | int iteration = 1000000; 35 | for (int i = 0; i < iteration; i++) 36 | { 37 | // 1 by 1 38 | for (int j = 0; j < 108; j++) 39 | { 40 | msgMan.ParseBytes(new byte[1] { data[j] }, 0, 1); 41 | } 42 | // sliced chunks 43 | msgMan.ParseBytes(data, 0, cut); 44 | msgMan.ParseBytes(data, cut, 108 - cut); 45 | } 46 | Assert.IsTrue(NumMsg == 6 * iteration); 47 | } 48 | 49 | 50 | 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /NetworkLibrary/TCP/Base/Core/IAsyncSession.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.Components.Statistics; 2 | using System; 3 | using System.Net; 4 | 5 | namespace NetworkLibrary.TCP.Base 6 | { 7 | internal interface IAsyncSession : IDisposable 8 | { 9 | /// 10 | /// Bytes received event 11 | /// 12 | event Action OnBytesRecieved; 13 | 14 | /// 15 | /// Called when session is closed. 16 | /// 17 | event Action OnSessionClosed; 18 | 19 | /// 20 | /// RemoteEnpoint of this sesssion 21 | /// 22 | IPEndPoint RemoteEndpoint { get; } 23 | 24 | /// 25 | /// Sends buffer asycronusly. 26 | /// 27 | /// 28 | void SendAsync(byte[] buffer); 29 | 30 | /// 31 | /// Sends buffer region asyncronusly 32 | /// 33 | /// 34 | /// 35 | /// 36 | void SendAsync(byte[] buffer, int offset, int count); 37 | 38 | /// 39 | /// Starts the session 40 | /// 41 | void StartSession(); 42 | 43 | /// 44 | /// Disconnects the client and disposes the resources. 45 | /// 46 | void EndSession(); 47 | 48 | /// 49 | /// gets the session statistics. 50 | /// 51 | /// 52 | SessionStatistics GetSessionStatistics(); 53 | 54 | } 55 | } -------------------------------------------------------------------------------- /NetworkLibrary/Utils/AsyncManualResetEvent.cs: -------------------------------------------------------------------------------- 1 | using System.Threading; 2 | using System.Threading.Tasks; 3 | 4 | 5 | 6 | namespace NetworkLibrary.Utils 7 | { 8 | public class AsyncManualResetEvent 9 | { 10 | private volatile TaskCompletionSource completionSource = new TaskCompletionSource(); 11 | 12 | /// 13 | /// Initializes a new instance of the class with 14 | /// a Boolean value indicating whether to set the initial state to signaled. 15 | /// 16 | /// if set to true [signaled]. 17 | public AsyncManualResetEvent(bool signaled) 18 | { 19 | if (signaled) 20 | completionSource.TrySetResult(true); 21 | } 22 | 23 | /// 24 | /// Waits the asynchronous. 25 | /// 26 | /// 27 | public Task WaitAsync() { return completionSource.Task; } 28 | 29 | /// 30 | /// Sets the state of the event to signaled, allowing one or more waiting tasks to proceed. 31 | /// 32 | public void Set() { completionSource.TrySetResult(true); } 33 | 34 | /// 35 | /// Sets the state of the event to non signaled, allowing one or more waiting tasks to await. 36 | /// 37 | public void Reset() 38 | { 39 | while (true) 40 | { 41 | var tcs = completionSource; 42 | if (!tcs.Task.IsCompleted || 43 | Interlocked.CompareExchange(ref completionSource, new TaskCompletionSource(), tcs) == tcs) 44 | return; 45 | } 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /NetworkLibrary/Components/Crypto/IAesEngine.cs: -------------------------------------------------------------------------------- 1 | namespace NetworkLibrary.Components.Crypto 2 | { 3 | public enum AesMode 4 | { 5 | /// 6 | /// No Encyption is used 7 | /// 8 | None, 9 | 10 | /// 11 | /// IV is generated wirh secure random and send as is. 12 | /// 16 byte overhead no authentication. 13 | /// Secure but no authentication 14 | /// 15 | CBCRandomIV, 16 | /// 17 | /// An encoded counter is send then passed through Cipher with different key to generate an IV. 18 | /// Secure but no authentication 19 | /// 20 | CBCCtrIV, 21 | /// 22 | /// CBC with counter mode and HMAC authentication. This is hw accelerated also on .Net standard. 23 | /// has more byte overhead than GCM. 24 | /// 25 | CBCCtrIVHMAC, 26 | /// 27 | /// Standard GCM with 14 byte tag. This mode is reccomended to be used 28 | /// Note that on .net standard 2 this mode is managed without HW acceleration. 29 | /// 30 | GCM 31 | } 32 | public interface IAesEngine 33 | { 34 | byte[] Decrypt(byte[] bytes); 35 | byte[] Decrypt(byte[] bytes, int offset, int count); 36 | int DecryptInto(byte[] source, int sourceOffset, int sourceCount, byte[] output, int outputOffset); 37 | byte[] Encrypt(byte[] bytes); 38 | byte[] Encrypt(byte[] bytes, int offset, int count); 39 | int EncryptInto(byte[] source, int sourceOffset, int sourceCount, byte[] output, int outputOffset); 40 | int EncryptInto(byte[] data1, int offset1, int count1, byte[] data2, int offset2, int count2, byte[] output, int outputOffset); 41 | } 42 | } -------------------------------------------------------------------------------- /Tests/ConsoleTest/UnitTests/ByteMessageParserTest.cs: -------------------------------------------------------------------------------- 1 | using CustomNetworkLib; 2 | using CustomNetworkLib.SocketEventArgsTests; 3 | using CustomNetworkLib.Utils; 4 | using Microsoft.VisualStudio.TestTools.UnitTesting; 5 | using System; 6 | using System.Diagnostics; 7 | using System.Linq; 8 | using System.Net.Sockets; 9 | using System.Threading; 10 | 11 | namespace UnitTests 12 | { 13 | [TestClass] 14 | public class ByteMessageParserTest 15 | { 16 | 17 | [TestMethod] 18 | public void TestMessageParser() 19 | { 20 | Stopwatch sw= new Stopwatch(); 21 | int NumMsg = 0; 22 | ByteMessageReader msgMan = new ByteMessageReader(new Guid(), 128000); 23 | msgMan.OnMessageReady += (byte[] msg, int off, int ct) => NumMsg++; 24 | 25 | byte[] data = new byte[108]; 26 | PrefixWriter.WriteInt32AsBytes(data, 0, 32); 27 | PrefixWriter.WriteInt32AsBytes(data, 36, 32); 28 | PrefixWriter.WriteInt32AsBytes(data, 72, 32); 29 | 30 | byte[][] data1 = new byte[108][]; 31 | for (int j = 0; j < 108; j++) 32 | { 33 | data1[j]=new byte[1] { data[j] }; 34 | } 35 | 36 | 37 | int cut = 22; 38 | int iteration = 100000; 39 | for (int i = 0; i < iteration; i++) 40 | { 41 | // 1 by 1 42 | for (int j = 0; j < 108; j++) 43 | { 44 | msgMan.ParseBytes(new byte[1] { data[j] }, 0, 1); 45 | } 46 | // sliced chunks 47 | msgMan.ParseBytes(data, 0, cut); 48 | msgMan.ParseBytes(data, cut, 108 - cut); 49 | } 50 | Assert.IsTrue(NumMsg == 6*iteration); 51 | } 52 | 53 | 54 | 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /NetworkLibrary/UDP/Jumbo/JumboModule.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.UDP.Reliable.Components; 2 | using System; 3 | using System.Threading; 4 | 5 | namespace NetworkLibrary.UDP.Jumbo 6 | { 7 | public class JumboModule 8 | { 9 | Receiver receiver; 10 | Sender sender; 11 | public Action SendToSocket; 12 | public Action MessageReceived; 13 | public JumboModule() 14 | { 15 | this.receiver = new Receiver(); 16 | this.sender = new Sender(); 17 | sender.OnSend = SendBytesToSocket; 18 | receiver.OnMessageExtracted = HandleExtractedMessage; 19 | } 20 | 21 | private void HandleExtractedMessage(byte[] arg1, int arg2, int arg3) 22 | { 23 | MessageReceived?.Invoke(arg1, arg2, arg3); 24 | } 25 | 26 | private void SendBytesToSocket(byte[] arg1, int arg2, int arg3) 27 | { 28 | SendToSocket?.Invoke(arg1, arg2, arg3); 29 | } 30 | 31 | public void HandleReceivedSegment(byte[] buffer, int offset, int count) 32 | { 33 | receiver.ProccesReceivedDatagram(buffer, offset, count); 34 | } 35 | 36 | public void Release() 37 | { 38 | SendToSocket = null; 39 | MessageReceived = null; 40 | sender.Release(); 41 | receiver.Release(); 42 | } 43 | public void Send(byte[] data, int offset, int count) 44 | { 45 | sender.ProcessBytes(data, offset, count); 46 | } 47 | internal void Send(in Segment s1, in Segment s2) 48 | { 49 | sender.ProcessBytes(in s1, in s2); 50 | } 51 | internal void Send(in SegmentUnsafe s1, in Segment s2) 52 | { 53 | sender.ProcessBytes(in s1, in s2); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /SerializedNetwork/MessagePackNetwork/Components/BufferWriter.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.Components; 2 | using System; 3 | using System.Buffers; 4 | 5 | namespace MessagePackNetwork.Components 6 | { 7 | internal struct BufferWriter : IBufferWriter 8 | { 9 | public PooledMemoryStream stream; 10 | 11 | public BufferWriter(PooledMemoryStream stream) 12 | { 13 | this.stream = stream; 14 | } 15 | 16 | public void SetStream(PooledMemoryStream stream) 17 | { 18 | this.stream = stream; 19 | } 20 | 21 | public void Advance(int count) 22 | { 23 | stream.Position += count; 24 | } 25 | 26 | public Memory GetMemory(int sizeHint = 0) 27 | { 28 | //if (sizeHint < 256) 29 | // sizeHint = 256; 30 | //stream.Position += sizeHint; 31 | //stream.Position -= sizeHint; 32 | //stream.Reserve(sizeHint); 33 | //var buffer = stream.GetBuffer(); 34 | stream.GetMemory(sizeHint, out var buffer, out int offset, out int count); 35 | return new Memory(buffer, offset, count); 36 | //return new Memory(buffer, (int)stream.Position, sizeHint); 37 | } 38 | 39 | public Span GetSpan(int sizeHint = 0) 40 | { 41 | //if (sizeHint < 256) 42 | // sizeHint = 256; 43 | //stream.Position += sizeHint; 44 | //stream.Position -= sizeHint; 45 | //stream.Reserve(sizeHint); 46 | //var buffer = stream.GetBuffer(); 47 | //return new Span(buffer, (int)stream.Position, sizeHint); 48 | 49 | stream.GetMemory(sizeHint, out var buffer, out int offset, out int count); 50 | return new Span(buffer, offset, count); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /NetworkLibrary/TCP/Generic/GenericBuffer.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.Components.MessageBuffer; 2 | using NetworkLibrary.MessageProtocol; 3 | using System; 4 | namespace NetworkLibrary.TCP.Generic 5 | { 6 | internal class GenericBuffer : MessageBuffer where S : ISerializer, new() 7 | { 8 | private readonly S serializer = new S(); 9 | public GenericBuffer(int maxIndexedMemory, bool writeLengthPrefix = true) : base(maxIndexedMemory, writeLengthPrefix) 10 | { 11 | } 12 | 13 | public bool TryEnqueueMessage(T instance) 14 | { 15 | 16 | lock (bufferMtex) 17 | { 18 | if (currentIndexedMemory < MaxIndexedMemory && !disposedValue) 19 | { 20 | TotalMessageDispatched++; 21 | 22 | if (writeLengthPrefix) 23 | { 24 | // offset 4 for lenght prefix (reserve) 25 | writeStream.Position32 += 4; 26 | } 27 | 28 | int initalPos = writeStream.Position32; 29 | serializer.Serialize(writeStream, instance); 30 | int msgLen = writeStream.Position32 - initalPos; 31 | 32 | if (writeLengthPrefix) 33 | { 34 | var lastPos = writeStream.Position32; 35 | 36 | writeStream.Position32 = initalPos - 4; 37 | writeStream.WriteIntUnchecked(msgLen); 38 | writeStream.Position32 = lastPos; 39 | 40 | // for the currentIndexedMemory 41 | msgLen += 4; 42 | } 43 | 44 | 45 | currentIndexedMemory += msgLen; 46 | return true; 47 | 48 | } 49 | } 50 | return false; 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /NetworkLibrary/TCP/ByteMessage/ByteMessageSession.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.Components; 2 | using NetworkLibrary.Components.MessageBuffer; 3 | using NetworkLibrary.Components.MessageProcessor.Unmanaged; 4 | using NetworkLibrary.TCP.Base; 5 | using System; 6 | using System.Net.Sockets; 7 | 8 | namespace NetworkLibrary.TCP.ByteMessage 9 | { 10 | internal class ByteMessageSession : TcpSession 11 | { 12 | ByteMessageReader messageManager; 13 | public ByteMessageSession(SocketAsyncEventArgs acceptedArg, Guid sessionId) : base(acceptedArg, sessionId) 14 | { 15 | } 16 | 17 | public override void StartSession() 18 | { 19 | messageManager = new ByteMessageReader( SocketRecieveBufferSize); 20 | messageManager.OnMessageReady += HandleMessage; 21 | 22 | base.StartSession(); 23 | } 24 | 25 | protected virtual void HandleMessage(byte[] buffer, int offset, int count) 26 | { 27 | base.HandleReceived(buffer, offset, count); 28 | } 29 | 30 | // We take the received from the base here put it on msg reader, 31 | // for each extracted message reader will call handle message, 32 | // which will call base HandleRecieveComplete to triger message received event. 33 | protected sealed override void HandleReceived(byte[] buffer, int offset, int count) 34 | { 35 | messageManager.ParseBytes(buffer, offset, count); 36 | } 37 | 38 | protected override IMessageQueue CreateMessageQueue() 39 | { 40 | if (UseQueue) 41 | { 42 | var q = new MessageQueue(MaxIndexedMemory, new DelimitedMessageWriter()); 43 | return q; 44 | } 45 | else 46 | { 47 | return new MessageBuffer(MaxIndexedMemory); 48 | } 49 | 50 | } 51 | 52 | 53 | } 54 | } 55 | 56 | -------------------------------------------------------------------------------- /NetworkLibrary/Utils/ByteCopy.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.CompilerServices; 3 | 4 | namespace NetworkLibrary.Utils 5 | { 6 | public class ByteCopy 7 | { 8 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 9 | public static unsafe byte[] ToArray(byte[] buffer, int offset, int count) 10 | { 11 | byte[] result = GetNewArray(count, false); 12 | 13 | fixed (byte* destination = result) 14 | { 15 | fixed (byte* message_ = &buffer[offset]) 16 | Buffer.MemoryCopy(message_, destination, count, count); 17 | } 18 | return result; 19 | } 20 | 21 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 22 | public static byte[] GetNewArray(int size = 65000, bool isPinned = false) 23 | { 24 | #if NET5_0_OR_GREATER 25 | //Console.WriteLine("AADSADSA"); 26 | return GC.AllocateUninitializedArray(size, pinned: isPinned); 27 | #else 28 | return new byte[size]; 29 | #endif 30 | } 31 | 32 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 33 | public static unsafe void BlockCopy(byte[] source, int sourceOffset, byte[] dest, int destinationOffset, int count) 34 | { 35 | //System.Buffer.BlockCopy(source, sourceOffset, dest, destinationOffset, count); 36 | fixed (byte* destination = &dest[destinationOffset]) 37 | { 38 | fixed (byte* message_ = &source[sourceOffset]) 39 | Buffer.MemoryCopy(message_, destination, count, count); 40 | } 41 | } 42 | 43 | 44 | internal static byte[] Merge(byte[] b1, byte[] b2) 45 | { 46 | var bf=GetNewArray(b1.Length + b2.Length); 47 | BlockCopy(b1, 0, bf, 0, b1.Length); 48 | BlockCopy(b2, 0, bf, b1.Length, b2.Length); 49 | return bf; 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /SerializedNetwork/BinarySerializerNetwork/Components/BinarySerializer.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.MessageProtocol; 2 | using System.IO; 3 | using System.Runtime.Serialization.Formatters.Binary; 4 | 5 | namespace BinarySerializerNetwork.Components 6 | { 7 | public class BinarySerializer : ISerializer 8 | { 9 | private BinaryFormatter serializer; 10 | 11 | public BinarySerializer() 12 | { 13 | serializer = new BinaryFormatter(); 14 | } 15 | 16 | public T Deserialize(Stream source) 17 | { 18 | return (T)serializer.Deserialize(source); 19 | } 20 | 21 | public T Deserialize(byte[] buffer, int offset, int count) 22 | { 23 | using (var stream = new MemoryStream(buffer, offset, count)) 24 | return (T)serializer.Deserialize(stream); 25 | } 26 | 27 | public MessageEnvelope Deserialize(byte[] buffer, int offset, int count) 28 | { 29 | return Deserialize(buffer, offset, count); 30 | } 31 | 32 | public void Serialize(Stream destination, T instance) 33 | { 34 | // var ms = new MemoryStream(); 35 | //serializer.Serialize(ms, instance); 36 | 37 | // var buf = ms.GetBuffer(); 38 | // destination.Write(buf, 0, buf.Length); 39 | serializer.Serialize(destination, instance); 40 | // destination.Position = destination.Length; 41 | } 42 | 43 | public byte[] Serialize(T instance) 44 | { 45 | using (var stream = new MemoryStream()) 46 | { 47 | serializer.Serialize(stream, instance); 48 | return stream.ToArray(); 49 | } 50 | 51 | 52 | } 53 | 54 | public void Serialize(Stream destination, MessageEnvelope instance) 55 | { 56 | Serialize(destination, instance); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /NetworkLibrary/TCP/AES/AesTcpServer.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.Components; 2 | using NetworkLibrary.TCP.Base; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Net; 6 | using System.Net.Sockets; 7 | using System.Text; 8 | 9 | namespace NetworkLibrary.TCP.AES 10 | { 11 | public class AesTcpServer : AsyncTcpServer 12 | { 13 | private ConcurrentAesAlgorithm algorithm; 14 | public AesTcpServer(int port):base(port) 15 | { } 16 | 17 | public AesTcpServer(IPEndPoint endpointToBind, ConcurrentAesAlgorithm aesAlgorithm) : base(endpointToBind) 18 | { 19 | if (aesAlgorithm == null) 20 | { 21 | 22 | } 23 | this.algorithm = aesAlgorithm; 24 | } 25 | 26 | private protected override IAsyncSession CreateSession(SocketAsyncEventArgs e, Guid sessionId) 27 | { 28 | var session = new AesTcpSession(e, sessionId, algorithm); 29 | session.socketSendBufferSize = ClientSendBufsize; 30 | session.SocketRecieveBufferSize = ClientReceiveBufsize; 31 | session.MaxIndexedMemory = MaxIndexedMemoryPerClient; 32 | session.DropOnCongestion = DropOnBackPressure; 33 | session.UseQueue = false; 34 | return session; 35 | 36 | } 37 | //public void SetAlgorithm(ConcurrentAesAlgorithm algorithm) 38 | //{ 39 | // this.algorithm = algorithm; 40 | // foreach (var ses in Sessions.Values) 41 | // { 42 | // ((AesTcpSession)ses).Algorithm = algorithm; 43 | // } 44 | //} 45 | 46 | 47 | internal void SendBytesToClient(Guid clientId, byte[] buffer, int offset, int count, byte[] buffer2, int offset2, int count2) 48 | { 49 | if(Sessions.TryGetValue(clientId, out var session)) 50 | { 51 | ((AesTcpSession)session).SendAsync(buffer, offset, count, buffer2, offset2, count2); 52 | } 53 | 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Protobuff/Components/ProtoSerializer.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary; 2 | using NetworkLibrary.Components; 3 | using NetworkLibrary.MessageProtocol; 4 | using NetworkLibrary.Utils; 5 | using ProtoBuf; 6 | using System; 7 | using System.IO; 8 | using System.Runtime.CompilerServices; 9 | 10 | namespace Protobuff.Components.Serialiser 11 | { 12 | public class ProtoSerializer : ISerializer 13 | { 14 | private ConcurrentObjectPool streamPool = new ConcurrentObjectPool(); 15 | 16 | public ProtoSerializer() 17 | { 18 | 19 | } 20 | 21 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 22 | public T Deserialize(Stream source) 23 | { 24 | return Serializer.Deserialize(source); 25 | } 26 | 27 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 28 | public T Deserialize(byte[] buffer, int offset, int count) 29 | { 30 | return Serializer.Deserialize(new ReadOnlySpan(buffer, offset, count)); 31 | } 32 | 33 | public MessageEnvelope Deserialize(byte[] buffer, int offset, int count) 34 | { 35 | return Serializer.Deserialize(new ReadOnlySpan(buffer, offset, count)); 36 | } 37 | 38 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 39 | public void Serialize(Stream destination, T instance) 40 | { 41 | Serializer.Serialize(destination, instance); 42 | } 43 | 44 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 45 | public byte[] Serialize(T instance) 46 | { 47 | var _stream = streamPool.RentObject(); 48 | _stream.Position = 0; 49 | Serializer.Serialize(_stream, instance); 50 | 51 | var buffer = _stream.GetBuffer(); 52 | var bytes = ByteCopy.ToArray(buffer, 0, (int)_stream.Position); 53 | 54 | _stream.Clear(); 55 | streamPool.ReturnObject(_stream); 56 | return bytes; 57 | } 58 | 59 | 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /NetworkLibrary/Utils/SharedMemoryStreamPool.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.Components; 2 | using System; 3 | 4 | namespace NetworkLibrary.Utils 5 | { 6 | public class SharerdMemoryStreamPool : IDisposable 7 | { 8 | private ConcurrentObjectPool pool = new ConcurrentObjectPool(); 9 | private static ConcurrentObjectPool poolStatic = new ConcurrentObjectPool(); 10 | private bool disposedValue; 11 | 12 | public PooledMemoryStream RentStream() 13 | { 14 | if (disposedValue) 15 | throw new ObjectDisposedException(nameof(SharerdMemoryStreamPool)); 16 | 17 | return pool.RentObject(); 18 | } 19 | 20 | public static PooledMemoryStream RentStreamStatic() 21 | { 22 | return poolStatic.RentObject(); 23 | } 24 | 25 | public void ReturnStream(PooledMemoryStream stream) 26 | { 27 | if (disposedValue) 28 | throw new ObjectDisposedException(nameof(SharerdMemoryStreamPool)); 29 | 30 | stream.Clear(); 31 | pool.ReturnObject(stream); 32 | } 33 | 34 | public static void ReturnStreamStatic(PooledMemoryStream stream) 35 | { 36 | stream.Clear(); 37 | poolStatic.ReturnObject(stream); 38 | } 39 | 40 | protected virtual void Dispose(bool disposing) 41 | { 42 | if (!disposedValue) 43 | { 44 | if (disposing) 45 | { 46 | for (int i = 0; i < pool.pool.Count; i++) 47 | { 48 | if (pool.pool.TryTake(out var stram)) 49 | stram.Dispose(); 50 | } 51 | } 52 | 53 | pool = null; 54 | disposedValue = true; 55 | } 56 | } 57 | 58 | public void Dispose() 59 | { 60 | Dispose(disposing: true); 61 | GC.SuppressFinalize(this); 62 | } 63 | } 64 | 65 | 66 | } 67 | -------------------------------------------------------------------------------- /Protobuff/Protobuff.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0;netstandard2.1;net5.0;net6.0;net7.0;net8.0 5 | True 6 | Protobuf.Network.Library 7 | Protobuf Network Library 8 | ReferenceType 9 | Message passing and P2P network library using protobuf .net 10 | https://github.com/ReferenceType/StandardNetworkLibrary 11 | Apache-2.0 12 | ProtobufNetworkLibrary 13 | 2.01 14 | 3.0.0 15 | 2.0.1 16 | 17 | True 18 | protobuf;network;p2p;holepunch;nat traversal;high performance;reliable udp 19 | Licence.txt 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | <_Parameter1>ConsoleTest 37 | 38 | 39 | 40 | 41 | True 42 | \ 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /Protobuff/P2P/Generic/StateManagemet/Server/ServerStateManager.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary; 2 | using NetworkLibrary.MessageProtocol; 3 | using System; 4 | 5 | namespace Protobuff.P2P.Generic.StateManagemet.Server 6 | { 7 | internal class ServerStateManager : StateManager where S : ISerializer, new() 8 | { 9 | SecureRelayServerBase server; 10 | 11 | public ServerStateManager(SecureRelayServerBase server) : base(server) 12 | { 13 | this.server = server; 14 | } 15 | 16 | public bool HandleMessage(Guid clientId, MessageEnvelope message) 17 | { 18 | switch (message.Header) 19 | { 20 | case Constants.Register: 21 | AddState(CreateConnectionState(clientId, message)); 22 | return true; 23 | 24 | default: 25 | return base.HandleMessage(message); 26 | } 27 | 28 | } 29 | 30 | 31 | // Connection state 32 | private IState CreateConnectionState(Guid clientId, MessageEnvelope message) 33 | { 34 | var stateId = Guid.NewGuid(); 35 | var state = new ServerConnectionState(clientId, stateId, this); 36 | state.Completed += OnServerConnectionStateCompleted; 37 | MessageEnvelope envelope = new MessageEnvelope() 38 | { 39 | IsInternal = true, 40 | Header = Constants.ServerRegisterAck, 41 | To = clientId, 42 | MessageId = stateId, 43 | Payload = server.ServerUdpInitKey 44 | }; 45 | 46 | server.SendAsyncMessage(clientId, envelope); 47 | return state; 48 | } 49 | 50 | private void OnServerConnectionStateCompleted(IState obj) 51 | { 52 | if (obj.Status == StateStatus.Completed) 53 | { 54 | var state = obj as ServerConnectionState; 55 | server.Register(state.clientId, state.remoteEndpoint, state.endpointTransferMsg.LocalEndpoints, state.random); 56 | } 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /NetworkLibrary/P2P/Constants.cs: -------------------------------------------------------------------------------- 1 | namespace NetworkLibrary.P2P 2 | { 3 | 4 | public class Constants 5 | { 6 | public const string Register = "1"; 7 | public const string ServerRegisterAck = "2"; 8 | public const string UdpInit = "3"; 9 | public const string ServerFinalizationCmd = "4"; 10 | public const string ClientFinalizationAck = "5"; 11 | public const string NotifyPeerListUpdate = "6"; 12 | 13 | //hp 14 | public const string InitiateHolepunch = "7"; 15 | public const string HolePunchSucces = "8"; 16 | public const string KeyTransfer = "9"; 17 | public const string HolpunchMessagesSent = "10"; 18 | public const string NotifyServerHolepunch = "11"; 19 | 20 | public const string Ping = "Ping"; 21 | public const string Pong = "Pong"; 22 | 23 | 24 | public const string RoomUpdate = "12"; 25 | public const string JoinRoom = "13"; 26 | public const string LeaveRoom = "14"; 27 | public const string GetAvailableRooms = "15"; 28 | public const string PeerDisconnected = "16"; 29 | public const string Rudp = "17"; 30 | public const string Rudp1 = "18"; 31 | public const string Rudp2 = "19"; 32 | public const string Judp = "20"; 33 | 34 | // key of a dict, picked some unusual control char. 35 | public const string RoomName = "\v"; 36 | 37 | public const string ReqTCPHP = "ReqTCPHP"; 38 | public const string TcpPortMap = "TcpPortMap"; 39 | public const string OkSendUdp = "OkSendUdp"; 40 | public const string ResendUdp = "ResendUdp"; 41 | public const string AckPortMap = "AckPortMap"; 42 | public const string TryConnect = "TryConnect"; 43 | public const string SwapToClient = "SwapToClient"; 44 | public const string FinalizeSuccess = "FinalizeSuccess"; 45 | public const string FinalizeFail = "FinalizeFail"; 46 | public const string Failed = "Failed"; 47 | public const string Success = "Success"; 48 | public const string InitTCPHPRemote = "InitTCPHPRemote"; 49 | 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /NetworkLibrary/MessageProtocol/Generic/Components/GenericMessageAwaiter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Threading.Tasks; 4 | 5 | namespace NetworkLibrary.MessageProtocol 6 | { 7 | public class GenericMessageAwaiter where E : IMessageEnvelope, new() 8 | { 9 | E timeoutResponse; 10 | ConcurrentDictionary> awaitingMessages 11 | = new ConcurrentDictionary>(); 12 | public GenericMessageAwaiter() 13 | { 14 | timeoutResponse = new E(); 15 | timeoutResponse.Header = "RequestTimedOut"; 16 | } 17 | 18 | public async Task RegisterWait(Guid messageId, int timeoutMs) 19 | { 20 | awaitingMessages[messageId] = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); 21 | var pending = awaitingMessages[messageId].Task; 22 | E returnMessage; 23 | 24 | var delay = Task.Delay(timeoutMs); 25 | if (await Task.WhenAny(pending, delay).ConfigureAwait(false) == pending) 26 | { 27 | // Task completed within timeout. 28 | returnMessage = pending.Result; 29 | } 30 | else 31 | { 32 | // timeout/cancellation logic 33 | returnMessage = timeoutResponse; 34 | 35 | } 36 | 37 | awaitingMessages.TryRemove(messageId, out _); 38 | return returnMessage; 39 | } 40 | 41 | public void ResponseArrived(E envelopedMessage) 42 | { 43 | if (awaitingMessages.TryGetValue(envelopedMessage.MessageId, out var completionSource)) 44 | { 45 | // lock(do a copy) because continiation will be async. 46 | envelopedMessage.LockBytes(); 47 | completionSource.TrySetResult(envelopedMessage); 48 | } 49 | } 50 | 51 | public bool IsWaiting(Guid messageId) 52 | { 53 | return awaitingMessages.TryGetValue(messageId, out _); 54 | } 55 | 56 | public void CancelWait(Guid messageId) 57 | { 58 | //todo 59 | } 60 | 61 | 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /MessagePack/Components/MessagePackSerializer.cs: -------------------------------------------------------------------------------- 1 | using MessagePack; 2 | using NetworkLibrary.Components; 3 | using System; 4 | using System.Buffers; 5 | using System.Collections.Generic; 6 | using System.IO; 7 | using System.Linq; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | 11 | namespace MessagePackNetwork.Components 12 | { 13 | public class MessagepackSerializer : NetworkLibrary.MessageProtocol.ISerializer 14 | { 15 | public MessagepackSerializer() 16 | { 17 | 18 | } 19 | 20 | public T Deserialize(Stream source) 21 | { 22 | var buff = ((PooledMemoryStream)source).GetBuffer(); 23 | return MessagePackSerializer.Deserialize(new ReadOnlyMemory(buff, 0, (int)source.Position)); 24 | } 25 | 26 | public T Deserialize(byte[] buffer, int offset, int count) 27 | { 28 | return MessagePackSerializer.Deserialize(new ReadOnlyMemory(buffer, offset, count)); 29 | } 30 | 31 | public void Serialize(Stream destination, T instance) 32 | { 33 | var wrt = new BufferWriter((PooledMemoryStream)destination); 34 | MessagePackSerializer.Serialize(wrt, instance); 35 | } 36 | 37 | public byte[] Serialize(T instance) 38 | { 39 | return MessagePackSerializer.Serialize(instance); 40 | } 41 | } 42 | 43 | internal readonly struct BufferWriter : IBufferWriter 44 | { 45 | public readonly PooledMemoryStream stream; 46 | 47 | public BufferWriter(PooledMemoryStream stream) 48 | { 49 | this.stream = stream; 50 | } 51 | 52 | public void Advance(int count) 53 | { 54 | stream.Position += count; 55 | } 56 | 57 | public Memory GetMemory(int sizeHint = 0) 58 | { 59 | stream.GetMemory(sizeHint, out var buffer, out int offset, out int count); 60 | return new Memory(buffer, offset, count); 61 | } 62 | 63 | public Span GetSpan(int sizeHint = 0) 64 | { 65 | stream.GetMemory(sizeHint, out var buffer, out int offset, out int count); 66 | return new Span(buffer, offset, count); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /NetworkLibrary/TCP/SSLCustom/CustomSslSession.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.Components; 2 | using NetworkLibrary.Components.Crypto.Algorithms; 3 | using NetworkLibrary.TCP.ByteMessage; 4 | using System; 5 | using System.Net.Sockets; 6 | 7 | namespace NetworkLibrary.TCP.SSL.Custom 8 | { 9 | internal class CustomSslSession : ByteMessageSession 10 | { 11 | AesCbcAlgorithm encryptor; 12 | //AesDecryptor processor; 13 | private AesMessageDecryptor decr; 14 | 15 | internal CustomSslSession(SocketAsyncEventArgs acceptedArg, Guid sessionId, byte[] aesKey) : base(acceptedArg, sessionId) 16 | { 17 | encryptor = new AesCbcAlgorithm(aesKey, aesKey); 18 | decr = new AesMessageDecryptor(encryptor); 19 | } 20 | 21 | public override void SendAsync(byte[] bytes) 22 | { 23 | 24 | base.SendAsync(bytes); 25 | //base.SendAsync(encryptor.Encrypt(bytes)); 26 | } 27 | 28 | 29 | protected override void HandleMessage(byte[] buffer, int offset, int count) 30 | { 31 | // here we are sure that encypted message is more or equal than original message. 32 | var decriptedAmount = encryptor.DecryptInto(buffer, offset, count, buffer, offset); 33 | base.HandleMessage(buffer, offset, decriptedAmount); 34 | 35 | //byte[] data = new byte[count]; 36 | //Buffer.BlockCopy(buffer, offset, data, 0, count); 37 | 38 | //decr.SetBuffer(ref buffer, offset); 39 | //decr.ProcessMessage(data); 40 | //base.HandleMessage(decr.Buffer, offset, decr.count); 41 | 42 | //var res = encryptor.Decrypt(buffer, offset, count); 43 | //base.HandleMessage(res, 0, res.Length); 44 | 45 | //byte[] data = new byte[count]; 46 | //Buffer.BlockCopy(buffer, offset, data, 0, count); 47 | //var am = processor.ProcessMessage(data, buffer, offset); 48 | //base.HandleMessage(buffer, offset, am); 49 | } 50 | 51 | protected override IMessageQueue CreateMessageQueue() 52 | { 53 | var a = new AesMessageEncryptor(algorithm: encryptor); 54 | var Q = new MessageQueue(MaxIndexedMemory, a); 55 | 56 | 57 | return Q; 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /NetworkLibrary/Utils/AsyncAutoResetEvent.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Threading.Tasks; 3 | 4 | namespace NetworkLibrary.Utils 5 | { 6 | public class AsyncAutoResetEvent 7 | { 8 | private readonly static Task completed = Task.FromResult(true); 9 | private readonly ConcurrentQueue> waiters = new ConcurrentQueue>(); 10 | private bool signaled; 11 | 12 | /// 13 | /// Initializes a new instance of the 14 | /// class with a Boolean value indicating whether to set the initial state to signaled. 15 | /// 16 | /// if set to true [signaled]. 17 | public AsyncAutoResetEvent(bool signaled = false) 18 | { 19 | this.signaled = signaled; 20 | } 21 | 22 | 23 | /// 24 | /// Switches state machine of the current task until the event is signaled, 25 | /// a signal. 26 | /// 27 | /// 28 | public Task WaitAsync() 29 | { 30 | lock (waiters) 31 | { 32 | if (signaled) 33 | { 34 | signaled = false; 35 | return completed; 36 | } 37 | else 38 | { 39 | var tcs = new TaskCompletionSource(); 40 | waiters.Enqueue(tcs); 41 | return tcs.Task; 42 | } 43 | } 44 | } 45 | 46 | /// 47 | /// Sets the state of the event to signaled, allowing one or more waiting tasks to proceed. 48 | /// 49 | public void Set() 50 | { 51 | TaskCompletionSource toRelease = null; 52 | lock (waiters) 53 | { 54 | if (waiters.Count > 0) 55 | { 56 | waiters.TryDequeue(out toRelease); 57 | } 58 | 59 | else if (!signaled) 60 | signaled = true; 61 | 62 | if (toRelease != null) 63 | toRelease.SetResult(true); 64 | } 65 | 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /NetworkLibrary/NetworkLibrary - Backup.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | true 6 | Standard.Network.Library 7 | True 8 | Standard Network Library 9 | High performance extensible network library optimised for high trafic messages 10 | 11 | https://github.com/ReferenceType/StandardNetworkLibrary 12 | https://github.com/ReferenceType/StandardNetworkLibrary 13 | RefrenceType 14 | Licence.txt 15 | Apache 2.0 16 | 1.0.7 17 | 1.0.5.0 18 | 1.0.5.0 19 | Task Syncronisation contexts are fixed to aviod possible deadlocks on some client applications such as WPF. 20 | 21 | 22 | 23 | False 24 | 25 | 26 | 27 | True 28 | 29 | 30 | 31 | 32 | 33 | <_Parameter1>UnitTests 34 | 35 | 36 | 37 | 38 | 39 | <_Parameter1>ConsoleTest 40 | 41 | 42 | 43 | 44 | 45 | 46 | PreserveNewest 47 | 48 | 49 | PreserveNewest 50 | 51 | 52 | 53 | 54 | 55 | 56 | True 57 | \ 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /SerializedNetwork/NetSerializerNetwork/Components/NetSerializer.cs: -------------------------------------------------------------------------------- 1 | using NetSerializer; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Threading; 6 | 7 | namespace NetSerializerNetwork.Components 8 | { 9 | public class NetSerialiser : NetworkLibrary.MessageProtocol.ISerializer 10 | { 11 | public T Deserialize(Stream source) 12 | { 13 | UpdateModels(typeof(T)); 14 | serializer.DeserializeDirect(source, out T value); 15 | return value; 16 | } 17 | 18 | public T Deserialize(byte[] buffer, int offset, int count) 19 | { 20 | UpdateModels(typeof(T)); 21 | 22 | var ms = new MemoryStream(buffer, offset, count); 23 | 24 | serializer.DeserializeDirect(ms, out T value); 25 | return value; 26 | 27 | 28 | } 29 | 30 | public void Serialize(Stream destination, T instance) 31 | { 32 | UpdateModels(typeof(T)); 33 | 34 | serializer.SerializeDirect(destination, instance); 35 | } 36 | 37 | public byte[] Serialize(T instance) 38 | { 39 | UpdateModels(typeof(T)); 40 | 41 | MemoryStream stream = new MemoryStream(); 42 | serializer.SerializeDirect(stream, instance); 43 | return stream.ToArray(); 44 | 45 | } 46 | 47 | static Dictionary map; 48 | static Serializer serializer; 49 | public NetSerialiser() 50 | { 51 | if (serializer == null) 52 | { 53 | serializer = new Serializer(new List { typeof(MessageEnvelope) }); 54 | map = serializer.GetTypeMap(); 55 | } 56 | 57 | } 58 | private static readonly object locker = new object(); 59 | private void UpdateModels(Type t) 60 | { 61 | if (!map.ContainsKey(t)) 62 | { 63 | lock (locker) 64 | { 65 | if (!map.ContainsKey(t)) 66 | { 67 | serializer.AddTypes(new List { t }); 68 | var mapLocal = serializer.GetTypeMap(); 69 | Interlocked.Exchange(ref map, mapLocal); 70 | } 71 | 72 | } 73 | 74 | } 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /NetSerializer/Components/NetSerialiser.cs: -------------------------------------------------------------------------------- 1 | using NetSerializer; 2 | using NetworkLibrary; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.IO; 6 | using System.Threading; 7 | 8 | namespace NetSerializerNetwork.Components 9 | { 10 | public class NetSerialiser : NetworkLibrary.MessageProtocol.ISerializer 11 | { 12 | public T Deserialize(Stream source) 13 | { 14 | UpdateModels(typeof(T)); 15 | serializer.DeserializeDirect(source, out T value); 16 | return value; 17 | } 18 | 19 | public T Deserialize(byte[] buffer, int offset, int count) 20 | { 21 | UpdateModels(typeof(T)); 22 | 23 | var ms = new MemoryStream(buffer, offset, count); 24 | 25 | serializer.DeserializeDirect(ms, out T value); 26 | return value; 27 | 28 | 29 | } 30 | 31 | public void Serialize(Stream destination, T instance) 32 | { 33 | UpdateModels(typeof(T)); 34 | 35 | serializer.SerializeDirect(destination, instance); 36 | } 37 | 38 | public byte[] Serialize(T instance) 39 | { 40 | UpdateModels(typeof(T)); 41 | 42 | MemoryStream stream = new MemoryStream(); 43 | serializer.SerializeDirect(stream, instance); 44 | return stream.ToArray(); 45 | 46 | } 47 | 48 | static Dictionary map; 49 | static Serializer serializer; 50 | public NetSerialiser() 51 | { 52 | if (serializer == null) 53 | { 54 | serializer = new Serializer(new List { typeof(MessageEnvelope) }); 55 | map = serializer.GetTypeMap(); 56 | } 57 | 58 | } 59 | private static readonly object locker = new object(); 60 | private void UpdateModels(Type t) 61 | { 62 | if (!map.ContainsKey(t)) 63 | { 64 | lock (locker) 65 | { 66 | if (!map.ContainsKey(t)) 67 | { 68 | serializer.AddTypes(new List { t }); 69 | var mapLocal = serializer.GetTypeMap(); 70 | Interlocked.Exchange(ref map, mapLocal); 71 | } 72 | 73 | } 74 | 75 | } 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /Protobuff/UDP/GenericSecureUdpMessageClient.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.Components; 2 | using NetworkLibrary.MessageProtocol; 3 | using NetworkLibrary.UDP.Secure; 4 | using NetworkLibrary.Utils; 5 | using System; 6 | 7 | namespace Protobuff.UDP 8 | { 9 | public class GenericSecureUdpMessageClient : SecureUdpClient 10 | where E : IMessageEnvelope, new() 11 | where S : ISerializer, new() 12 | { 13 | public Action OnMessageReceived; 14 | private readonly GenericMessageSerializer serialiser = new GenericMessageSerializer(); 15 | private readonly SharerdMemoryStreamPool streamPool = new SharerdMemoryStreamPool(); 16 | 17 | public GenericSecureUdpMessageClient(ConcurrentAesAlgorithm algorithm) : base(algorithm) { } 18 | 19 | protected override void HandleDecrypedBytes(byte[] buffer, int offset, int count) 20 | { 21 | var msg = serialiser.DeserialiseEnvelopedMessage(buffer, offset, count); 22 | OnMessageReceived?.Invoke(msg); 23 | } 24 | 25 | public void SendAsyncMessage(E message) 26 | { 27 | var serialisationStream = streamPool.RentStream(); 28 | serialiser.EnvelopeMessageWithBytes(serialisationStream, 29 | message, message.Payload, message.PayloadOffset, message.PayloadCount); 30 | 31 | SendAsync(serialisationStream.GetBuffer(), 0, (int)serialisationStream.Position); 32 | streamPool.ReturnStream(serialisationStream); 33 | } 34 | 35 | public void SendAsyncMessage(E message, T innerMessage) 36 | { 37 | var serialisationStream = streamPool.RentStream(); 38 | serialiser.EnvelopeMessageWithInnerMessage(serialisationStream, message, innerMessage); 39 | 40 | SendAsync(serialisationStream.GetBuffer(), 0, (int)serialisationStream.Position); 41 | streamPool.ReturnStream(serialisationStream); 42 | } 43 | 44 | public void SendAsyncMessage(E message, byte[] payload, int offset, int count) 45 | { 46 | var serialisationStream = streamPool.RentStream(); 47 | serialiser.EnvelopeMessageWithBytes(serialisationStream, message, payload, offset, count); 48 | 49 | SendAsync(serialisationStream.GetBuffer(), 0, (int)serialisationStream.Position); 50 | streamPool.ReturnStream(serialisationStream); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /NetworkLibrary/UDP/Reliable/Test/Mockup.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.UDP.Reliable.Components; 2 | using NetworkLibrary.Utils; 3 | using System; 4 | using System.Threading; 5 | 6 | namespace NetworkLibrary.UDP.Reliable.Test 7 | { 8 | public class Mockup 9 | { 10 | SenderModule s = new SenderModule(); 11 | ReceiverModule r = new ReceiverModule(); 12 | Random random = new Random(); 13 | public Action OnReceived; 14 | public bool RemoveNoiseSend = true; 15 | public bool RemoveNoiseFeedback = true; 16 | public int getArrivedCount() => r.arrived.Count; 17 | public int getActiveCount() => s.pendingPackages.Count; 18 | public Mockup() 19 | { 20 | s.SendRequested += EmulateNoisySend; 21 | r.SendFeedback += EmulateNoisyFeedback; 22 | r.OnMessageReceived += MessageReceived; 23 | } 24 | 25 | 26 | private void EmulateNoisyFeedback(byte[] arg1, int arg2, int arg3) 27 | { 28 | if (RemoveNoiseFeedback || random.Next(0, 100) % 30 != 0) 29 | { 30 | var buff = ByteCopy.ToArray(arg1, arg2, arg3); 31 | ThreadPool.UnsafeQueueUserWorkItem((x) => { s.HandleFeedback(buff, 0); }, null); 32 | } 33 | else 34 | { 35 | 36 | } 37 | return; 38 | 39 | } 40 | 41 | private void EmulateNoisySend(byte[] arg1, int arg2, int arg3) 42 | { 43 | if (RemoveNoiseSend || random.Next(0, 100) % 20 != 0) 44 | { 45 | var buff = ByteCopy.ToArray(arg1, arg2, arg3); 46 | 47 | ThreadPool.UnsafeQueueUserWorkItem((m) => 48 | { 49 | r.HandleBytes(buff, 0, buff.Length); 50 | } 51 | , null); 52 | } 53 | else 54 | { 55 | 56 | } 57 | return; 58 | 59 | } 60 | 61 | public void SendTest(byte[] arg1, int arg2, int arg3) 62 | { 63 | s.ProcessBytesToSend(arg1, arg2, arg3); 64 | } 65 | public void SendTest(Segment first, Segment second) 66 | { 67 | s.ProcessBytesToSend(first, second); 68 | } 69 | private void MessageReceived(byte[] arg1, int arg2, int arg3) 70 | { 71 | OnReceived?.Invoke(arg1, arg2, arg3); 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /NetworkLibrary/Components/Crypto/Algorithms/NoEncyption.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.Utils; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace NetworkLibrary.Components.Crypto.Algorithms 7 | { 8 | internal class NoEncyption : IAesAlgorithm 9 | { 10 | public int DecryptorInputBlockSize => 0; 11 | 12 | public int DecryptorOutputBlockSize => 0; 13 | 14 | public int EncryptorInputBlockSize => 0; 15 | 16 | public int EncryptorOutputBlockSize => 0; 17 | 18 | public byte[] Decrypt(byte[] bytes) 19 | { 20 | return bytes; 21 | } 22 | 23 | public byte[] Decrypt(byte[] bytes, int offset, int count) 24 | { 25 | return ByteCopy.ToArray(bytes, offset, count); 26 | } 27 | 28 | public int DecryptInto(byte[] source, int sourceOffset, int sourceCount, byte[] output, int outputOffset) 29 | { 30 | ByteCopy.BlockCopy(source, sourceOffset, output, outputOffset, sourceCount); 31 | return sourceCount; 32 | } 33 | 34 | public void Dispose() 35 | { 36 | 37 | } 38 | 39 | public byte[] Encrypt(byte[] bytes) 40 | { 41 | return Encrypt(bytes, 0, bytes.Length); 42 | } 43 | 44 | public byte[] Encrypt(byte[] bytes, int offset, int count) 45 | { 46 | var buf = BufferPool.RentBuffer(count); 47 | ByteCopy.BlockCopy(bytes, offset, buf, 0, count); 48 | var res = ByteCopy.ToArray(buf, 0, count); 49 | BufferPool.ReturnBuffer(buf); 50 | return res; 51 | } 52 | 53 | public int EncryptInto(byte[] source, int sourceOffset, int sourceCount, byte[] output, int outputOffset) 54 | { 55 | 56 | ByteCopy.BlockCopy(source, sourceOffset, output, outputOffset, sourceCount); 57 | return sourceCount; 58 | } 59 | 60 | public int EncryptInto(byte[] data1, int offset1, int count1, byte[] data2, int offset2, int count2, byte[] output, int outputOffset) 61 | { 62 | ByteCopy.BlockCopy(data1, offset1, output, outputOffset, count1); 63 | ByteCopy.BlockCopy(data2, offset2, output, outputOffset + count1, count2); 64 | return count1 + count2; 65 | } 66 | 67 | public int GetEncriptorOutputSize(int inputSize) 68 | { 69 | return inputSize; 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /SerializedNetwork/DataContractNetwork/Components/DataContractSerializer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.IO; 4 | using System.Runtime.Serialization; 5 | 6 | namespace DataContractNetwork.Components 7 | { 8 | public class DataContractSerialiser : NetworkLibrary.MessageProtocol.ISerializer 9 | { 10 | static ConcurrentDictionary seralizers = new ConcurrentDictionary(); 11 | static DataContractSerializer serializer; 12 | public DataContractSerialiser() 13 | { 14 | if (serializer == null) 15 | { 16 | serializer = new DataContractSerializer(typeof(MessageEnvelope)); 17 | seralizers.TryAdd(typeof(MessageEnvelope), serializer); 18 | } 19 | 20 | } 21 | 22 | private DataContractSerializer GetSerializer() 23 | { 24 | if (seralizers.TryGetValue(typeof(T), out var serializer)) 25 | { 26 | return serializer; 27 | } 28 | serializer = new DataContractSerializer(typeof(MessageEnvelope)); 29 | seralizers.TryAdd(typeof(T), serializer); 30 | return serializer; 31 | } 32 | 33 | public T Deserialize(Stream source) 34 | { 35 | DataContractSerializer serializer = GetSerializer(); 36 | return (T)serializer.ReadObject(source); 37 | } 38 | 39 | 40 | 41 | public T Deserialize(byte[] buffer, int offset, int count) 42 | { 43 | DataContractSerializer serializer = GetSerializer(); 44 | return (T)serializer.ReadObject(new MemoryStream(buffer, offset, count)); 45 | } 46 | 47 | public void Serialize(Stream destination, T instance) 48 | { 49 | DataContractSerializer serializer = GetSerializer(); 50 | //var ms = new MemoryStream(); 51 | 52 | //serializer.WriteObject(ms, instance); 53 | //destination.Write(ms.GetBuffer(), 0, (int)ms.Length); 54 | 55 | serializer.WriteObject(destination, instance); 56 | } 57 | 58 | public byte[] Serialize(T instance) 59 | { 60 | DataContractSerializer serializer = GetSerializer(); 61 | var ms = new MemoryStream(); 62 | serializer.WriteObject(ms, instance); 63 | return ms.ToArray(); 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /NetworkLibrary/TCP/AES/AesTcpClient.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.Components; 2 | using NetworkLibrary.TCP.Base; 3 | using NetworkLibrary.TCP.ByteMessage; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Net.Sockets; 7 | using System.Text; 8 | 9 | namespace NetworkLibrary.TCP.AES 10 | { 11 | 12 | 13 | public class AesTcpClient : AsyncTpcClient 14 | { 15 | private AesTcpSession sessionInternal; 16 | private ConcurrentAesAlgorithm algorithm; 17 | 18 | public AesTcpClient(ConcurrentAesAlgorithm algorithm) 19 | { 20 | this.algorithm = algorithm; 21 | } 22 | 23 | public AesTcpClient(Socket clientSocket, ConcurrentAesAlgorithm algorithm) 24 | { 25 | 26 | this.algorithm = algorithm; 27 | SetConnectedSocket(clientSocket,ScatterGatherConfig.UseBuffer); 28 | } 29 | 30 | private protected override IAsyncSession CreateSession(SocketAsyncEventArgs e, Guid sessionId) 31 | { 32 | var session = new AesTcpSession(e, sessionId,algorithm); 33 | session.socketSendBufferSize = SocketSendBufferSize; 34 | session.SocketRecieveBufferSize = SocketRecieveBufferSize; 35 | session.MaxIndexedMemory = MaxIndexedMemory; 36 | session.DropOnCongestion = DropOnCongestion; 37 | session.UseQueue = false; 38 | sessionInternal = session; 39 | return session; 40 | 41 | } 42 | //public void SetAlgorithm(ConcurrentAesAlgorithm algorithm) 43 | //{ 44 | // this.algorithm = algorithm; 45 | // sessionInternal.Algorithm = algorithm; 46 | //} 47 | private protected override IAsyncSession CreateSession(Socket socket, Guid sessionId) 48 | { 49 | var session = new AesTcpSession(socket, sessionId, algorithm); 50 | session.socketSendBufferSize = SocketSendBufferSize; 51 | session.SocketRecieveBufferSize = SocketRecieveBufferSize; 52 | session.MaxIndexedMemory = MaxIndexedMemory; 53 | session.DropOnCongestion = DropOnCongestion; 54 | session.UseQueue = false; 55 | sessionInternal = session; 56 | return session; 57 | } 58 | 59 | public void SendAsync(byte[] data1, int offset1, int count1, byte[] data2, int offset2, int count2) 60 | { 61 | sessionInternal.SendAsync(data1, offset1, count1, data2, offset2, count2); 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /SerializedNetwork/ProtobufNetwork/ProtoSerializer.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.Components; 2 | using NetworkLibrary.MessageProtocol; 3 | using NetworkLibrary.Utils; 4 | using ProtoBuf; 5 | using System; 6 | using System.IO; 7 | using System.Runtime.CompilerServices; 8 | 9 | namespace ProtobufNetwork 10 | { 11 | public class ProtoSerializer : ISerializer 12 | { 13 | private ConcurrentObjectPool streamPool = new ConcurrentObjectPool(); 14 | //private RuntimeTypeModel Serializer; 15 | 16 | public ProtoSerializer() 17 | { 18 | ProtoBuf.Serializer.PrepareSerializer(); 19 | //ProtoBuf.Serializer.PrepareSerializer(); 20 | ProtoBuf.Serializer.PrepareSerializer(); 21 | // Serializer = RuntimeTypeModel.Default; 22 | } 23 | 24 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 25 | public T Deserialize(Stream source) 26 | { 27 | return Serializer.Deserialize(source); 28 | } 29 | 30 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 31 | public T Deserialize(byte[] buffer, int offset, int count) 32 | { 33 | //fixed (byte* startPointer = &buffer[offset]) 34 | //{ 35 | // var span = new ReadOnlySpan(startPointer, count); 36 | // return Serializer.Deserialize(span); 37 | //} 38 | 39 | return Serializer.Deserialize(new ReadOnlySpan(buffer, offset, count)); 40 | } 41 | 42 | public MessageEnvelope Deserialize(byte[] buffer, int offset, int count) 43 | { 44 | return Serializer.Deserialize(new ReadOnlySpan(buffer, offset, count)); 45 | } 46 | 47 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 48 | public void Serialize(Stream destination, T instance) 49 | { 50 | Serializer.Serialize(destination, instance); 51 | } 52 | 53 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 54 | public byte[] Serialize(T instance) 55 | { 56 | var _stream = streamPool.RentObject(); 57 | _stream.Position = 0; 58 | Serializer.Serialize(_stream, instance); 59 | 60 | var buffer = _stream.GetBuffer(); 61 | var bytes = ByteCopy.ToArray(buffer, 0, (int)_stream.Position); 62 | 63 | _stream.Clear(); 64 | streamPool.ReturnObject(_stream); 65 | return bytes; 66 | } 67 | 68 | public void Serialize(Stream destination, MessageEnvelope instance) 69 | { 70 | Serializer.Serialize(destination, instance); 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /NetworkLibrary/P2P/Components/StateManagemet/Server/ServerStateManager.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.MessageProtocol; 2 | using NetworkLibrary.P2P.Components.StateManagemet.Server; 3 | using NetworkLibrary.P2P.Generic; 4 | using NetworkLibrary.Utils; 5 | using System; 6 | 7 | namespace NetworkLibrary.P2P.Components.StateManagement.Server 8 | { 9 | internal class ServerStateManager : StateManager where S : ISerializer, new() 10 | { 11 | SecureRelayServerBase server; 12 | 13 | public ServerStateManager(SecureRelayServerBase server) : base(server) 14 | { 15 | this.server = server; 16 | } 17 | 18 | public bool HandleMessage(Guid clientId, MessageEnvelope message) 19 | { 20 | switch (message.Header) 21 | { 22 | case Constants.Register: 23 | CreateConnectionState(clientId, message); 24 | return true; 25 | case Constants.ReqTCPHP: 26 | CreateTcpHPState(message); 27 | return true; 28 | default: 29 | return base.HandleMessage(message); 30 | } 31 | 32 | } 33 | 34 | 35 | // Connection state 36 | private IState CreateConnectionState(Guid clientId, MessageEnvelope message) 37 | { 38 | var stateId = Guid.NewGuid(); 39 | var state = new ServerConnectionState(clientId, stateId, this); 40 | state.Completed += OnServerConnectionStateCompleted; 41 | AddState(state); 42 | MessageEnvelope envelope = new MessageEnvelope() 43 | { 44 | IsInternal = true, 45 | Header = Constants.ServerRegisterAck, 46 | To = clientId, 47 | MessageId = stateId, 48 | Payload = server.ServerUdpInitKey 49 | }; 50 | 51 | server.SendAsyncMessage(clientId, envelope); 52 | return state; 53 | } 54 | 55 | private void OnServerConnectionStateCompleted(IState obj) 56 | { 57 | if (obj.Status == StateStatus.Completed) 58 | { 59 | var state = obj as ServerConnectionState; 60 | server.Register(state.clientId, state.remoteEndpoint, state.endpointTransferMsg.LocalEndpoints, state.random); 61 | } 62 | } 63 | 64 | private ServerTcpHolepunchState CreateTcpHPState(MessageEnvelope message) 65 | { 66 | var state = new ServerTcpHolepunchState(this,message.MessageId); 67 | AddState(state); 68 | state.Initialize(message); 69 | MiniLogger.Log(MiniLogger.LogLevel.Info, "Created tcp holepunch state"); 70 | // room server needs to know this completion. maybe? 71 | return state; 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /NetworkLibrary/Components/Crypto/Certificate/CertificateGenerator.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Security.Cryptography; 4 | using System.Security.Cryptography.X509Certificates; 5 | using NetworkLibrary.Components.Crypto.Certificate.Native; 6 | 7 | namespace NetworkLibrary.Components.Crypto.Certificate 8 | 9 | { 10 | public static class CertificateGenerator 11 | { 12 | public static X509Certificate2 GenerateSelfSignedCertificate() 13 | { 14 | 15 | #if NETSTANDARD2_1_OR_GREATER || NETCOREAPP3_1_OR_GREATER 16 | return GenerateSelfSignedDotNet(); 17 | #else 18 | return GenerateSelfSignedNative(); 19 | #endif 20 | 21 | } 22 | 23 | private static X509Certificate2 GenerateSelfSignedNative() 24 | { 25 | if (Environment.OSVersion.Platform != PlatformID.Win32NT) 26 | throw new PlatformNotSupportedException("Certificate generation on .Net standard 2.0 is only supported in windows"); 27 | 28 | X509Certificate2 cert; 29 | using (CryptContext ctx = new CryptContext()) 30 | { 31 | ctx.Open(); 32 | 33 | cert = ctx.CreateSelfSignedCertificate( 34 | new SelfSignedCertProperties 35 | { 36 | IsPrivateKeyExportable = true, 37 | KeyBitLength = 2048, 38 | Name = new X500DistinguishedName("cn=localhost"), 39 | ValidFrom = DateTime.Today.AddDays(-1), 40 | ValidTo = DateTime.Today.AddYears(1), 41 | }); 42 | 43 | 44 | } 45 | return new X509Certificate2(cert.Export(X509ContentType.Pfx)); 46 | 47 | } 48 | #if NETSTANDARD2_1_OR_GREATER || NETCOREAPP3_1_OR_GREATER 49 | private static X509Certificate2 GenerateSelfSignedDotNet() 50 | { 51 | using (RSA parent = RSA.Create(2048)) 52 | { 53 | CertificateRequest parentReq = new CertificateRequest( 54 | "CN=localhost", 55 | parent, 56 | HashAlgorithmName.SHA256, 57 | RSASignaturePadding.Pkcs1); 58 | 59 | parentReq.CertificateExtensions.Add( 60 | new X509BasicConstraintsExtension(true, false, 0, true)); 61 | 62 | parentReq.CertificateExtensions.Add( 63 | new X509SubjectKeyIdentifierExtension(parentReq.PublicKey, false)); 64 | 65 | X509Certificate2 parentCert = parentReq.CreateSelfSigned( 66 | DateTimeOffset.UtcNow.AddDays(-45), 67 | DateTimeOffset.UtcNow.AddDays(365)); 68 | return new X509Certificate2(parentCert.Export(X509ContentType.Pfx)); 69 | } 70 | } 71 | 72 | #endif 73 | 74 | } 75 | } 76 | 77 | 78 | 79 | -------------------------------------------------------------------------------- /Protobuff/UDP/EncryptedUdpProtoClient.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary; 2 | using NetworkLibrary.Components; 3 | using NetworkLibrary.MessageProtocol; 4 | using NetworkLibrary.UDP.Secure; 5 | using NetworkLibrary.Utils; 6 | using Protobuff.Components.Serialiser; 7 | using System; 8 | 9 | namespace Protobuff.UDP 10 | { 11 | internal class EncryptedUdpProtoClient : SecureUdpClient 12 | { 13 | public Action OnMessageReceived; 14 | private readonly GenericMessageSerializer serialiser = new GenericMessageSerializer(); 15 | private readonly SharerdMemoryStreamPool streamPool = new SharerdMemoryStreamPool(); 16 | 17 | public EncryptedUdpProtoClient(ConcurrentAesAlgorithm algorithm) : base(algorithm) { } 18 | 19 | protected override void HandleDecrypedBytes(byte[] buffer, int offset, int count) 20 | { 21 | var msg = serialiser.DeserialiseEnvelopedMessage(buffer, offset, count); 22 | OnMessageReceived?.Invoke(msg); 23 | } 24 | 25 | public void SendAsyncMessage(MessageEnvelope message) 26 | { 27 | var serialisationStream = streamPool.RentStream(); 28 | serialiser.EnvelopeMessageWithBytes(serialisationStream, 29 | message, message.Payload, message.PayloadOffset, message.PayloadCount); 30 | 31 | SendAsync(serialisationStream.GetBuffer(), 0, (int)serialisationStream.Position); 32 | streamPool.ReturnStream(serialisationStream); 33 | } 34 | 35 | public void SendAsyncMessage(MessageEnvelope message, T innerMessage) where T : IProtoMessage 36 | { 37 | var serialisationStream = streamPool.RentStream(); 38 | serialiser.EnvelopeMessageWithInnerMessage(serialisationStream, message, innerMessage); 39 | 40 | SendAsync(serialisationStream.GetBuffer(), 0, (int)serialisationStream.Position); 41 | streamPool.ReturnStream(serialisationStream); 42 | } 43 | 44 | public void SendAsyncMessage(MessageEnvelope message, byte[] payload, int offset, int count) 45 | { 46 | var serialisationStream = streamPool.RentStream(); 47 | serialiser.EnvelopeMessageWithBytes(serialisationStream, message, payload, offset, count); 48 | 49 | SendAsync(serialisationStream.GetBuffer(), 0, (int)serialisationStream.Position); 50 | streamPool.ReturnStream(serialisationStream); 51 | } 52 | 53 | public void SendAsyncMessage(MessageEnvelope message, Action serializationCallback) 54 | { 55 | var serialisationStream = streamPool.RentStream(); 56 | serialiser.EnvelopeMessageWithInnerMessage(serialisationStream, message, serializationCallback); 57 | 58 | SendAsync(serialisationStream.GetBuffer(), 0, (int)serialisationStream.Position); 59 | streamPool.ReturnStream(serialisationStream); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /NetworkLibrary/UDP/Secure/SecureUdpClient.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.Components; 2 | using NetworkLibrary.Utils; 3 | using System; 4 | 5 | namespace NetworkLibrary.UDP.Secure 6 | { 7 | public class SecureUdpClient : AsyncUdpClient 8 | { 9 | public ConcurrentAesAlgorithm algorithm; 10 | public SecureUdpClient(ConcurrentAesAlgorithm algorithm, int port) : base(port) 11 | { 12 | this.algorithm = algorithm; 13 | } 14 | 15 | public SecureUdpClient(ConcurrentAesAlgorithm algorithm) 16 | { 17 | this.algorithm = algorithm; 18 | } 19 | 20 | public void SwapAlgorith(ConcurrentAesAlgorithm algorithm) 21 | { 22 | this.algorithm = algorithm; 23 | } 24 | 25 | protected override void HandleBytesReceived(byte[] buffer, int offset, int count) 26 | { 27 | var decryptBuffer = BufferPool.RentBuffer(count + 256); 28 | try 29 | { 30 | if (algorithm != null) 31 | { 32 | var decriptedAmount = algorithm.DecryptInto(buffer, offset, count, decryptBuffer, 0); 33 | HandleDecrypedBytes(decryptBuffer, 0, decriptedAmount); 34 | } 35 | else 36 | { 37 | HandleDecrypedBytes(buffer, offset, count); 38 | } 39 | 40 | } 41 | catch (Exception e) 42 | { 43 | MiniLogger.Log(MiniLogger.LogLevel.Error, nameof(SecureUdpClient) + " Encountered an error whie handling incoming bytes: " + e.Message); 44 | } 45 | finally 46 | { 47 | BufferPool.ReturnBuffer(decryptBuffer); 48 | } 49 | } 50 | 51 | protected virtual void HandleDecrypedBytes(byte[] buffer, int offset, int amount) 52 | { 53 | base.HandleBytesReceived(buffer, offset, amount); 54 | } 55 | 56 | public override void SendAsync(byte[] bytes, int offset, int count) 57 | { 58 | var buffer = BufferPool.RentBuffer(count + 256); 59 | try 60 | { 61 | if (algorithm != null) 62 | { 63 | int amount = algorithm.EncryptInto(bytes, offset, count, buffer, 0); 64 | base.SendAsync(buffer, 0, amount); 65 | } 66 | else 67 | { 68 | base.SendAsync(bytes, offset, count); 69 | } 70 | 71 | 72 | } 73 | catch (Exception ex) 74 | { 75 | MiniLogger.Log(MiniLogger.LogLevel.Error, "AnErroroccured while sending udp message: " + ex.Message); 76 | } 77 | finally { BufferPool.ReturnBuffer(buffer); } 78 | 79 | } 80 | 81 | //public void SendPreEncypyedBytes(byte[] buffer, int offset, int count) 82 | //{ 83 | // base.SendAsync(buffer, offset, count); 84 | 85 | //} 86 | 87 | 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /NetworkLibrary/NetworkLibrary.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0;netstandard2.1;net5.0;net6.0;net7.0;net8.0 5 | true 6 | Standard.Network.Library 7 | True 8 | Standard Network Library 9 | High performance extensible network library optimised for high trafic messages 10 | 11 | https://github.com/ReferenceType/StandardNetworkLibrary 12 | https://github.com/ReferenceType/StandardNetworkLibrary 13 | RefrenceType 14 | Apache 2.0 15 | 3.0.0 16 | 2.0.1 17 | 2.0.1 18 | For release notes check out: https://github.com/ReferenceType/StandardNetworkLibrary 19 | 20 | Licence.txt 21 | tcp;udp;rupd;p2p;holepucnh;room;server;client;network;library;socket; 22 | 23 | 24 | 25 | False 26 | 27 | 28 | 29 | True 30 | 31 | 32 | 33 | 9999 34 | 35 | 36 | 37 | 9999 38 | 39 | 40 | 41 | 42 | 43 | <_Parameter1>UnitTests 44 | 45 | 46 | 47 | 48 | 49 | <_Parameter1>ConsoleTest 50 | 51 | 52 | 53 | 54 | 55 | True 56 | \ 57 | 58 | 59 | 60 | 61 | 62 | 63 | PreserveNewest 64 | 65 | 66 | PreserveNewest 67 | 68 | 69 | 70 | 71 | 72 | 73 | True 74 | \ 75 | 76 | 77 | 78 | 79 | -------------------------------------------------------------------------------- /NetworkLibrary/Components/MessageBuffer/MessageQueue.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.Utils; 2 | using System.Collections.Concurrent; 3 | using System.Runtime.CompilerServices; 4 | using System.Threading; 5 | 6 | namespace NetworkLibrary.Components 7 | { 8 | internal sealed class MessageQueue : IMessageQueue where T : IMessageProcessor 9 | { 10 | public int CurrentIndexedMemory => Interlocked.CompareExchange(ref currentIndexedMemory,0,0); 11 | public long TotalMessageDispatched => totalMessageFlushed; 12 | 13 | internal ConcurrentQueue SendQueue = new ConcurrentQueue(); 14 | private int MaxIndexedMemory; 15 | private int currentIndexedMemory = 0; 16 | private T processor; 17 | private bool flushNext; 18 | private long totalMessageFlushed; 19 | 20 | public MessageQueue(int maxIndexedMemory, T processor) 21 | { 22 | MaxIndexedMemory = maxIndexedMemory; 23 | this.processor = processor; 24 | } 25 | 26 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 27 | public bool TryEnqueueMessage(byte[] bytes) 28 | { 29 | if ( Volatile.Read(ref currentIndexedMemory) < MaxIndexedMemory) 30 | { 31 | Interlocked.Add(ref currentIndexedMemory, bytes.Length); 32 | SendQueue.Enqueue(bytes); 33 | return true; 34 | } 35 | return false; 36 | } 37 | 38 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 39 | public bool TryFlushQueue(ref byte[] buffer, int offset, out int amountWritten) 40 | { 41 | amountWritten = 0; 42 | processor.SetBuffer(ref buffer, offset); 43 | if (flushNext) 44 | { 45 | if (!processor.Flush()) 46 | { 47 | processor.GetBuffer(out buffer, out _, out amountWritten); 48 | return true; 49 | } 50 | flushNext = false; 51 | } 52 | int memcount = 0; 53 | while (SendQueue.TryDequeue(out byte[] bytes)) 54 | { 55 | totalMessageFlushed++; 56 | 57 | memcount += bytes.Length; 58 | if (!processor.ProcessMessage(bytes)) 59 | { 60 | flushNext = true; 61 | break; 62 | }; 63 | 64 | } 65 | Interlocked.Add(ref currentIndexedMemory,-memcount); 66 | processor.GetBuffer(out buffer, out _, out amountWritten); 67 | return amountWritten != 0; 68 | 69 | } 70 | 71 | public bool IsEmpty() 72 | { 73 | return SendQueue.IsEmpty && !processor.IsHoldingMessage; 74 | } 75 | 76 | public bool TryEnqueueMessage(byte[] bytes, int offset, int count) 77 | { 78 | var array = ByteCopy.ToArray(bytes, offset, count); 79 | return TryEnqueueMessage(array); 80 | } 81 | 82 | public void Dispose() 83 | { 84 | processor.Dispose(); 85 | } 86 | 87 | public void Flush() { } 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /NetworkLibrary/P2P/Components/StateManagemet/Server/ServerConnectionState.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.P2P.Components.HolePunch; 2 | using System; 3 | using System.Net; 4 | using System.Security.Cryptography; 5 | using System.Threading; 6 | 7 | namespace NetworkLibrary.P2P.Components.StateManagement.Server 8 | { 9 | 10 | class ServerConnectionState : IState 11 | { 12 | 13 | public event Action Completed; 14 | public Guid StateId { get; } 15 | 16 | public StateStatus Status => currentStatus; 17 | 18 | internal Guid clientId; 19 | internal IPEndPoint remoteEndpoint; 20 | internal EndpointTransferMessage endpointTransferMsg; 21 | internal byte[] random; 22 | 23 | private int currentState = 0; 24 | private StateStatus currentStatus = StateStatus.Pending; 25 | private StateManager server; 26 | 27 | public ServerConnectionState(Guid clientId, Guid stateId, StateManager server) 28 | { 29 | this.server = server; 30 | this.clientId = clientId; 31 | StateId = stateId; 32 | } 33 | 34 | public void HandleMessage(MessageEnvelope message) 35 | { 36 | if (message.Header == Constants.ClientFinalizationAck) 37 | { 38 | HandleClientFinalization(message); 39 | } 40 | } 41 | public void HandleMessage(IPEndPoint remoteEndpoint, MessageEnvelope message) 42 | { 43 | if (message.Header == Constants.UdpInit) 44 | { 45 | HandleUdpInitMessage(remoteEndpoint, message); 46 | } 47 | } 48 | 49 | public void HandleUdpInitMessage(IPEndPoint remoteEndpoint, MessageEnvelope message) 50 | { 51 | if (Interlocked.CompareExchange(ref currentState, 1, 0) == 0) 52 | { 53 | this.remoteEndpoint = remoteEndpoint; 54 | endpointTransferMsg = KnownTypeSerializer.DeserializeEndpointTransferMessage(message.Payload, message.PayloadOffset); 55 | 56 | random = new byte[16]; 57 | var rng = RandomNumberGenerator.Create(); 58 | rng.GetNonZeroBytes(random); 59 | rng.Dispose(); 60 | 61 | MessageEnvelope envelope = new MessageEnvelope 62 | { 63 | IsInternal = true, 64 | Header = Constants.ServerFinalizationCmd, 65 | Payload = random, 66 | MessageId = StateId, 67 | }; 68 | 69 | server.SendTcpMessage(clientId, envelope); 70 | } 71 | } 72 | 73 | public void HandleClientFinalization(MessageEnvelope message) 74 | { 75 | Release(true); 76 | } 77 | 78 | private int isReleased = 0; 79 | public void Release(bool isCompletedSuccessfully) 80 | { 81 | if (Interlocked.CompareExchange(ref isReleased, 1, 0) == 0) 82 | { 83 | if (isCompletedSuccessfully) 84 | currentStatus = StateStatus.Completed; 85 | else 86 | currentStatus = StateStatus.Failed; 87 | Completed?.Invoke(this); 88 | Completed = null; 89 | } 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /NetworkLibrary/UDP/Reliable/Components/Timer.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.Utils; 2 | using System.Collections.Concurrent; 3 | using System.Diagnostics; 4 | using System.Threading; 5 | 6 | 7 | 8 | namespace NetworkLibrary.UDP.Reliable.Components 9 | { 10 | public class Timer 11 | { 12 | static readonly ConcurrentDictionary activeTimers = new ConcurrentDictionary(); 13 | public static int TickFrequency = 10; 14 | 15 | static Timer() 16 | { 17 | TimedObject.activeTimers = activeTimers; 18 | StartTimer(); 19 | } 20 | 21 | private static void StartTimer() 22 | { 23 | Looper(); 24 | } 25 | static Stopwatch time = new Stopwatch(); 26 | private static void Looper() 27 | { 28 | #if Debug 29 | Task.Run(async () => { 30 | while (true) 31 | { 32 | await Task.Delay(1000); 33 | Console.WriteLine("pending timers : " + activeTimers.Count); 34 | 35 | } 36 | 37 | }); 38 | #endif 39 | Thread t = new Thread(() => 40 | { 41 | time.Start(); 42 | while (true) 43 | { 44 | Thread.Sleep(TickFrequency); 45 | try 46 | { 47 | Tick((int)time.ElapsedMilliseconds); 48 | time.Restart(); 49 | } 50 | catch { } 51 | } 52 | 53 | }); 54 | t.Start(); 55 | 56 | } 57 | private static object locker = new object(); 58 | private static void Tick(int dt) 59 | { 60 | if (activeTimers.Count == 0) 61 | return; 62 | 63 | foreach (var item in activeTimers) 64 | { 65 | item.Key.Tick(dt); 66 | } 67 | 68 | // Parallel.ForEach(activeTimers,t=>t.Key.Tick(dt)); 69 | } 70 | 71 | 72 | 73 | public static bool Register(TimedObject instance) 74 | { 75 | if (!activeTimers.TryAdd(instance, null)) 76 | { 77 | MiniLogger.Log(MiniLogger.LogLevel.Error, "Unable to add timer instance, there is a serious concurrency error " + instance.GetType().Name); 78 | return false; 79 | } 80 | return true; 81 | } 82 | 83 | public static bool Remove(TimedObject instance) 84 | { 85 | if (!activeTimers.TryRemove(instance, out _)) 86 | { 87 | // MiniLogger.Log(MiniLogger.LogLevel.Error, "Unable to Remove timer instance, there is a serious concurrency error"+ instance.GetType().Name); 88 | return false; 89 | } 90 | return true; 91 | } 92 | 93 | } 94 | 95 | public abstract class TimedObject 96 | { 97 | public static ConcurrentDictionary activeTimers; 98 | 99 | public abstract void Tick(int dt); 100 | 101 | 102 | protected virtual void OnTimeout() 103 | { 104 | activeTimers.TryRemove(this, out _); 105 | } 106 | 107 | } 108 | 109 | } 110 | -------------------------------------------------------------------------------- /NetworkLibrary/MessageProtocol/Fast/Wrapper/GenericMessageClientWrapper.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.Components.Statistics; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Runtime.CompilerServices; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace NetworkLibrary.MessageProtocol.Fast 9 | { 10 | public class GenericMessageClientWrapper 11 | where S : ISerializer, new() 12 | { 13 | private MessageClient client; 14 | public Action OnMessageReceived; 15 | public Action OnDisconnected; 16 | 17 | private GenericMessageSerializer serialiser = new GenericMessageSerializer(); 18 | 19 | public GenericMessageClientWrapper() 20 | { 21 | client = new MessageClient(); 22 | client.OnMessageReceived += HandleMessageReceived; 23 | client.OnDisconnected += Disconnected; 24 | client.MaxIndexedMemory = 128000000; 25 | 26 | client.GatherConfig = ScatterGatherConfig.UseBuffer; 27 | 28 | } 29 | 30 | private void HandleMessageReceived(MessageEnvelope message) 31 | { 32 | OnMessageReceived?.Invoke(message); 33 | } 34 | 35 | public void Connect(string host, int port) 36 | { 37 | client.Connect(host, port); 38 | } 39 | public Task ConnectAsync(string host, int port) 40 | { 41 | return client.ConnectAsyncAwaitable(host, port); 42 | } 43 | 44 | public void Disconnect() 45 | { 46 | client.Disconnect(); 47 | } 48 | 49 | private void Disconnected() 50 | { 51 | OnDisconnected?.Invoke(); 52 | } 53 | #region Send 54 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 55 | public void SendAsyncMessage(MessageEnvelope message) 56 | { 57 | client.SendAsyncMessage(message); 58 | } 59 | 60 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 61 | public void SendAsyncMessage(MessageEnvelope message, byte[] buffer, int offset, int count) 62 | { 63 | client.SendAsyncMessage(message, buffer, offset, count); 64 | } 65 | 66 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 67 | public void SendAsyncMessage(MessageEnvelope message, T payload) 68 | { 69 | client.SendAsyncMessage(message, payload); 70 | } 71 | 72 | #endregion Send 73 | 74 | #region SendAndWait 75 | public Task SendMessageAndWaitResponse(MessageEnvelope message, int timeoutMs = 10000) 76 | { 77 | return client.SendMessageAndWaitResponse(message, timeoutMs); 78 | } 79 | 80 | public Task SendMessageAndWaitResponse(MessageEnvelope message, T payload, int timeoutMs = 10000) 81 | { 82 | return client.SendMessageAndWaitResponse(message, payload, timeoutMs); 83 | } 84 | 85 | public Task SendMessageAndWaitResponse(MessageEnvelope message, byte[] buffer, int offset, int count, int timeoutMs = 10000) 86 | { 87 | return client.SendMessageAndWaitResponse(message, buffer, offset, count, timeoutMs); 88 | } 89 | #endregion 90 | 91 | public void GetStatistics(out TcpStatistics stats) 92 | { 93 | client.GetStatistics(out stats); 94 | } 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /SerializedNetwork/JsonNetwork/JsonMessageClient.cs: -------------------------------------------------------------------------------- 1 | using JsonMessageNetwork.Components; 2 | using JsonMessageNetwork.Internal; 3 | using NetworkLibrary.Components.Statistics; 4 | using NetworkLibrary.MessageProtocol; 5 | using System; 6 | using System.Runtime.CompilerServices; 7 | using System.Threading.Tasks; 8 | 9 | namespace JsonMessageNetwork 10 | { 11 | public class JsonMessageClient 12 | { 13 | public Action OnMessageReceived; 14 | public Action OnDisconnected; 15 | 16 | private ClientServer client; 17 | private GenericMessageSerializer serialiser = new GenericMessageSerializer(); 18 | 19 | public JsonMessageClient() 20 | { 21 | client = new ClientServer(); 22 | client.OnMessageReceived += HandleMessageReceived; 23 | client.OnDisconnected += Disconnected; 24 | client.MaxIndexedMemory = 128000000; 25 | 26 | client.GatherConfig = ScatterGatherConfig.UseBuffer; 27 | 28 | } 29 | 30 | private void HandleMessageReceived(MessageEnvelope message) 31 | { 32 | OnMessageReceived?.Invoke(message); 33 | } 34 | 35 | public void Connect(string host, int port) 36 | { 37 | client.Connect(host, port); 38 | } 39 | public Task ConnectAsync(string host, int port) 40 | { 41 | return client.ConnectAsyncAwaitable(host, port); 42 | } 43 | 44 | public void Disconnect() 45 | { 46 | client.Disconnect(); 47 | } 48 | 49 | private void Disconnected() 50 | { 51 | OnDisconnected?.Invoke(); 52 | } 53 | #region Send 54 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 55 | public void SendAsyncMessage(MessageEnvelope message) 56 | { 57 | client.SendAsyncMessage(message); 58 | } 59 | 60 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 61 | public void SendAsyncMessage(MessageEnvelope message, byte[] buffer, int offset, int count) 62 | { 63 | client.SendAsyncMessage(message, buffer, offset, count); 64 | } 65 | 66 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 67 | public void SendAsyncMessage(MessageEnvelope message, T payload) 68 | { 69 | client.SendAsyncMessage(message, payload); 70 | } 71 | 72 | #endregion Send 73 | 74 | #region SendAndWait 75 | public Task SendMessageAndWaitResponse(MessageEnvelope message, int timeoutMs = 10000) 76 | { 77 | return client.SendMessageAndWaitResponse(message, timeoutMs); 78 | } 79 | 80 | public Task SendMessageAndWaitResponse(MessageEnvelope message, T payload, int timeoutMs = 10000) 81 | { 82 | return client.SendMessageAndWaitResponse(message, payload, timeoutMs); 83 | } 84 | 85 | public Task SendMessageAndWaitResponse(MessageEnvelope message, byte[] buffer, int offset, int count, int timeoutMs = 10000) 86 | { 87 | return client.SendMessageAndWaitResponse(message, buffer, offset, count, timeoutMs); 88 | } 89 | #endregion 90 | 91 | 92 | 93 | public void GetStatistics(out TcpStatistics stats) 94 | { 95 | client.GetStatistics(out stats); 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /NetworkLibrary/TCP/SSLCustom/CustomSslClient.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.TCP.Base; 2 | using NetworkLibrary.TCP.ByteMessage; 3 | using System; 4 | using System.Net.Security; 5 | using System.Net.Sockets; 6 | using System.Security.Cryptography.X509Certificates; 7 | using System.Security.Cryptography; 8 | using NetworkLibrary.Utils; 9 | 10 | namespace NetworkLibrary.TCP.SSL.Custom 11 | { 12 | [Obsolete("Do not use this class, only for test")] 13 | // authenticate with tls, send with aes. 14 | public class CustomSslClient : ByteMessageTcpClient 15 | { 16 | private X509Certificate2 certificate; 17 | public CustomSslClient(X509Certificate2 certificate) 18 | { 19 | this.certificate = certificate; 20 | } 21 | 22 | private protected override IAsyncSession CreateSession(SocketAsyncEventArgs e, Guid sessionId) 23 | { 24 | var session = new CustomSslSession(e, sessionId, (byte[])e.UserToken); 25 | session.socketSendBufferSize = SocketSendBufferSize; 26 | session.SocketRecieveBufferSize = SocketRecieveBufferSize; 27 | session.MaxIndexedMemory = MaxIndexedMemory; 28 | session.DropOnCongestion = DropOnCongestion; 29 | session.UseQueue = true; 30 | return session; 31 | } 32 | 33 | protected override void HandleConnected(SocketAsyncEventArgs e) 34 | { 35 | #if NET6_0_OR_GREATER 36 | 37 | //var sock = e.ConnectSocket; 38 | //using (ECDiffieHellmanCng alice = new ECDiffieHellmanCng()) 39 | //{ 40 | 41 | // alice.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; 42 | // alice.HashAlgorithm = CngAlgorithm.Sha256; 43 | // var alicePublicKey = alice.PublicKey.ToByteArray(); 44 | 45 | // sock.Send(alicePublicKey); 46 | 47 | // byte[] b = new byte[140]; 48 | // int amount = sock.Receive(b); 49 | 50 | // var bobPk = b; 51 | // CngKey bobKey = CngKey.Import(bobPk, CngKeyBlobFormat.EccPublicBlob); 52 | // var privateKey = alice.DeriveKeyMaterial(bobKey); 53 | 54 | // e.UserToken = ByteCopy.ToArray(privateKey,0,16); 55 | //} 56 | //base.HandleConnected(e); 57 | //return; 58 | #endif 59 | 60 | // do the ssl validation certs, 61 | // get your aes symetric key, 62 | var sslStream = new SslStream(new NetworkStream(e.ConnectSocket, false), false, ValidateCeriticate); 63 | sslStream.AuthenticateAsClient("example.com", 64 | new X509CertificateCollection(new[] { certificate }), System.Security.Authentication.SslProtocols.Tls12, true); 65 | 66 | byte[] aesKey = new byte[16]; 67 | sslStream.Read(aesKey, 0, 16); 68 | e.UserToken = aesKey; 69 | // ack 70 | sslStream.Write(new byte[1]); 71 | sslStream.Flush(); 72 | 73 | sslStream.Close(); 74 | sslStream.Dispose(); 75 | 76 | base.HandleConnected(e); 77 | } 78 | 79 | protected virtual bool ValidateCeriticate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) 80 | { 81 | if (sslPolicyErrors == SslPolicyErrors.None || sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors) 82 | return true; 83 | return false; 84 | } 85 | 86 | } 87 | 88 | } 89 | -------------------------------------------------------------------------------- /SerializedNetwork/ProtobufNetwork/ProtoClient.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.Components.Statistics; 2 | using NetworkLibrary.MessageProtocol; 3 | using System; 4 | using System.Runtime.CompilerServices; 5 | using System.Threading.Tasks; 6 | 7 | namespace ProtobufNetwork 8 | { 9 | public class ProtoClient 10 | { 11 | public Action OnMessageReceived; 12 | public Action OnDisconnected; 13 | 14 | private ProtoClientInternal client; 15 | //private ConcurrentProtoSerialiser serialiser = new ConcurrentProtoSerialiser(); 16 | private GenericMessageSerializer serialiser = new GenericMessageSerializer(); 17 | 18 | public ProtoClient() 19 | { 20 | client = new ProtoClientInternal(); 21 | client.OnMessageReceived += HandleMessageReceived; 22 | client.OnDisconnected += Disconnected; 23 | client.MaxIndexedMemory = 128000000; 24 | 25 | client.GatherConfig = ScatterGatherConfig.UseBuffer; 26 | 27 | } 28 | 29 | private void HandleMessageReceived(MessageEnvelope message) 30 | { 31 | OnMessageReceived?.Invoke(message); 32 | } 33 | 34 | public void Connect(string host, int port) 35 | { 36 | client.Connect(host, port); 37 | } 38 | public Task ConnectAsync(string host, int port) 39 | { 40 | return client.ConnectAsyncAwaitable(host, port); 41 | } 42 | 43 | public void Disconnect() 44 | { 45 | client.Disconnect(); 46 | } 47 | 48 | private void Disconnected() 49 | { 50 | OnDisconnected?.Invoke(); 51 | } 52 | #region Send 53 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 54 | public void SendAsyncMessage(MessageEnvelope message) 55 | { 56 | client.SendAsyncMessage(message); 57 | } 58 | 59 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 60 | public void SendAsyncMessage(MessageEnvelope message, byte[] buffer, int offset, int count) 61 | { 62 | client.SendAsyncMessage(message, buffer, offset, count); 63 | } 64 | 65 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 66 | public void SendAsyncMessage(MessageEnvelope message, T payload) 67 | { 68 | client.SendAsyncMessage(message, payload); 69 | } 70 | 71 | #endregion Send 72 | 73 | #region SendAndWait 74 | public Task SendMessageAndWaitResponse(MessageEnvelope message, int timeoutMs = 10000) 75 | { 76 | return client.SendMessageAndWaitResponse(message, timeoutMs); 77 | } 78 | 79 | public Task SendMessageAndWaitResponse(MessageEnvelope message, T payload, int timeoutMs = 10000) 80 | { 81 | return client.SendMessageAndWaitResponse(message, payload, timeoutMs); 82 | } 83 | 84 | public Task SendMessageAndWaitResponse(MessageEnvelope message, byte[] buffer, int offset, int count, int timeoutMs = 10000) 85 | { 86 | return client.SendMessageAndWaitResponse(message, buffer, offset, count, timeoutMs); 87 | } 88 | #endregion 89 | 90 | 91 | 92 | public void GetStatistics(out TcpStatistics stats) 93 | { 94 | client.GetStatistics(out stats); 95 | } 96 | 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /NetworkLibrary/TCP/Generic/GenericSession.cs: -------------------------------------------------------------------------------- 1 | using NetworkLibrary.Components; 2 | using NetworkLibrary.MessageProtocol; 3 | using NetworkLibrary.TCP.Base; 4 | using System; 5 | using System.Net.Sockets; 6 | using System.Runtime.CompilerServices; 7 | using System.Threading; 8 | 9 | namespace NetworkLibrary.TCP.Generic 10 | { 11 | internal class GenericSession : TcpSession 12 | where S : ISerializer, new() 13 | { 14 | protected GenericBuffer mq; 15 | private ByteMessageReader reader; 16 | private readonly bool writeMsgLenghtPrefix; 17 | public GenericSession(SocketAsyncEventArgs acceptedArg, Guid sessionId, bool writeMsgLenghtPrefix = true) : base(acceptedArg, sessionId) 18 | { 19 | this.writeMsgLenghtPrefix = writeMsgLenghtPrefix; 20 | reader = new ByteMessageReader(); 21 | reader.OnMessageReady += HandleMessage; 22 | UseQueue = false; 23 | } 24 | 25 | private GenericBuffer GetMesssageQueue() 26 | { 27 | return new GenericBuffer(MaxIndexedMemory, writeMsgLenghtPrefix); 28 | } 29 | 30 | protected sealed override IMessageQueue CreateMessageQueue() 31 | { 32 | mq = GetMesssageQueue(); 33 | return mq; 34 | } 35 | 36 | private void HandleMessage(byte[] arg1, int arg2, int arg3) 37 | { 38 | base.HandleReceived(arg1, arg2, arg3); 39 | } 40 | 41 | protected override void HandleReceived(byte[] buffer, int offset, int count) 42 | { 43 | if (writeMsgLenghtPrefix) 44 | reader.ParseBytes(buffer, offset, count); 45 | else 46 | base.HandleReceived(buffer, offset, count); 47 | } 48 | 49 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 50 | public void SendAsync(T message) 51 | { 52 | if (IsSessionClosing()) 53 | return; 54 | try 55 | { 56 | SendAsyncInternal(message); 57 | } 58 | catch { if (!IsSessionClosing()) throw; } 59 | } 60 | 61 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 62 | private void SendAsyncInternal(T message) 63 | { 64 | enqueueLock.Take(); 65 | if (IsSessionClosing()) 66 | ReleaseSendResourcesIdempotent(); 67 | if (SendSemaphore.IsTaken() && mq.TryEnqueueMessage(message)) 68 | { 69 | enqueueLock.Release(); 70 | return; 71 | } 72 | enqueueLock.Release(); 73 | 74 | if (DropOnCongestion && SendSemaphore.IsTaken()) 75 | return; 76 | 77 | SendSemaphore.Take(); 78 | if (IsSessionClosing()) 79 | { 80 | ReleaseSendResourcesIdempotent(); 81 | SendSemaphore.Release(); 82 | return; 83 | } 84 | 85 | // you have to push it to queue because queue also does the processing. 86 | mq.TryEnqueueMessage(message); 87 | mq.TryFlushQueue(ref sendBuffer, 0, out int amountWritten); 88 | FlushSendBuffer(0, amountWritten); 89 | 90 | } 91 | protected override void ReleaseReceiveResources() 92 | { 93 | base.ReleaseReceiveResources(); 94 | Interlocked.Exchange(ref mq, null)?.Dispose(); 95 | Interlocked.Exchange(ref reader, null)?.ReleaseResources(); 96 | } 97 | } 98 | } 99 | --------------------------------------------------------------------------------