commit 3a79f40b59d4c683b306328d437ffbf7c388c3c3 parent fdd6d7311a07321ef393cfc5981b31f7274bd5c8 Author: Mikolaj Lenczewski <mikolaj.lenczewski308@gmail.com> Date: Fri, 12 Jun 2020 15:31:04 +0100 Added basic initial localisation, and also implemented user input for examples Diffstat:
19 files changed, 465 insertions(+), 55 deletions(-)
diff --git a/NetSharp/NetSharp/AssemblyAttributes.cs b/NetSharp/NetSharp/AssemblyAttributes.cs @@ -1,10 +1,5 @@ -using System.Runtime.CompilerServices; +using System.Resources; +using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("NetSharpExamples", AllInternalsVisible = true)] - -namespace NetSharp -{ - internal static class AssemblyAttributes - { - } -} -\ No newline at end of file +[assembly: NeutralResourcesLanguage("en")] +\ No newline at end of file diff --git a/NetSharp/NetSharp/NetSharp.csproj b/NetSharp/NetSharp/NetSharp.csproj @@ -6,13 +6,13 @@ <Configurations>Debug;Release</Configurations> </PropertyGroup> - <PropertyGroup> + <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'"> + <DocumentationFile>NetSharp.xml</DocumentationFile> <GeneratePackageOnBuild>true</GeneratePackageOnBuild> <PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance> - <NeutralLanguage>en</NeutralLanguage> <Authors>Mikołaj Lenczewski</Authors> <Company>NetSharp</Company> - <Version>0.1.2</Version> + <Version>0.1.4</Version> <PackageLicenseFile>LICENSE</PackageLicenseFile> <PackageProjectUrl>https://github.com/EnderRifter/NetSharp</PackageProjectUrl> <Description>A networking library for C#, focusing on performance and built on top of SocketAsyncEventArgs.</Description> @@ -23,10 +23,6 @@ <SymbolPackageFormat>snupkg</SymbolPackageFormat> </PropertyGroup> - <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'"> - <DocumentationFile>NetSharp.xml</DocumentationFile> - </PropertyGroup> - <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <DocumentationFile>NetSharp.xml</DocumentationFile> <DefineConstants>DEBUG;TRACE</DefineConstants> @@ -48,4 +44,22 @@ <PackagePath></PackagePath> </None> </ItemGroup> + + <ItemGroup> + <Compile Update="Properties\Resources.Designer.cs"> + <DesignTime>True</DesignTime> + <AutoGen>True</AutoGen> + <DependentUpon>Resources.resx</DependentUpon> + </Compile> + </ItemGroup> + + <ItemGroup> + <EmbeddedResource Update="Properties\Resources.pl-PL.resx"> + <Generator>ResXFileCodeGenerator</Generator> + </EmbeddedResource> + <EmbeddedResource Update="Properties\Resources.resx"> + <Generator>ResXFileCodeGenerator</Generator> + <LastGenOutput>Resources.Designer.cs</LastGenOutput> + </EmbeddedResource> + </ItemGroup> </Project> \ No newline at end of file diff --git a/NetSharp/NetSharp/NetSharp.xml b/NetSharp/NetSharp/NetSharp.xml @@ -4,6 +4,32 @@ <name>NetSharp</name> </assembly> <members> + <member name="T:NetSharp.Properties.Resources"> + <summary> + A strongly-typed resource class, for looking up localized strings, etc. + </summary> + </member> + <member name="P:NetSharp.Properties.Resources.ResourceManager"> + <summary> + Returns the cached ResourceManager instance used by this class. + </summary> + </member> + <member name="P:NetSharp.Properties.Resources.Culture"> + <summary> + Overrides the current thread's CurrentUICulture property for all + resource lookups using this strongly typed resource class. + </summary> + </member> + <member name="P:NetSharp.Properties.Resources.RawDatagramSizeError"> + <summary> + Looks up a localized string similar to The datagram size must be between 0 and 65507 bytes. + </summary> + </member> + <member name="P:NetSharp.Properties.Resources.RawStreamMessageSizeUnderflow"> + <summary> + Looks up a localized string similar to The maximum pooled message size must be greater than 0 bytes. + </summary> + </member> <member name="M:NetSharp.Raw.Datagram.RawDatagramNetworkReader.#ctor(System.Net.Sockets.Socket@,NetSharp.Raw.Datagram.RawDatagramRequestHandler,System.Net.EndPoint,System.Int32,System.Int32,System.UInt32)"> <inheritdoc /> </member> diff --git a/NetSharp/NetSharp/Properties/Resources.Designer.cs b/NetSharp/NetSharp/Properties/Resources.Designer.cs @@ -0,0 +1,81 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// </auto-generated> +//------------------------------------------------------------------------------ + +namespace NetSharp.Properties { + using System; + + + /// <summary> + /// A strongly-typed resource class, for looking up localized strings, etc. + /// </summary> + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// <summary> + /// Returns the cached ResourceManager instance used by this class. + /// </summary> + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("NetSharp.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// <summary> + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// </summary> + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// <summary> + /// Looks up a localized string similar to The datagram size must be between 0 and 65507 bytes. + /// </summary> + internal static string RawDatagramSizeError { + get { + return ResourceManager.GetString("RawDatagramSizeError", resourceCulture); + } + } + + /// <summary> + /// Looks up a localized string similar to The maximum pooled message size must be greater than 0 bytes. + /// </summary> + internal static string RawStreamMessageSizeUnderflow { + get { + return ResourceManager.GetString("RawStreamMessageSizeUnderflow", resourceCulture); + } + } + } +} diff --git a/NetSharp/NetSharp/Properties/Resources.pl-PL.resx b/NetSharp/NetSharp/Properties/Resources.pl-PL.resx @@ -0,0 +1,126 @@ +<?xml version="1.0" encoding="utf-8"?> +<root> + <!-- + Microsoft ResX Schema + + Version 2.0 + + The primary goals of this format is to allow a simple XML format + that is mostly human readable. The generation and parsing of the + various data types are done through the TypeConverter classes + associated with the data types. + + Example: + + ... ado.net/XML headers & schema ... + <resheader name="resmimetype">text/microsoft-resx</resheader> + <resheader name="version">2.0</resheader> + <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> + <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> + <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> + <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> + <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> + <value>[base64 mime encoded serialized .NET Framework object]</value> + </data> + <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> + <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> + <comment>This is a comment</comment> + </data> + + There are any number of "resheader" rows that contain simple + name/value pairs. + + Each data row contains a name, and value. The row also contains a + type or mimetype. Type corresponds to a .NET class that support + text/value conversion through the TypeConverter architecture. + Classes that don't support this are serialized and stored with the + mimetype set. + + The mimetype is used for serialized objects, and tells the + ResXResourceReader how to depersist the object. This is currently not + extensible. For a given mimetype the value must be set accordingly: + + Note - application/x-microsoft.net.object.binary.base64 is the format + that the ResXResourceWriter will generate, however the reader can + read any of the formats listed below. + + mimetype: application/x-microsoft.net.object.binary.base64 + value : The object must be serialized with + : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter + : and then encoded with base64 encoding. + + mimetype: application/x-microsoft.net.object.soap.base64 + value : The object must be serialized with + : System.Runtime.Serialization.Formatters.Soap.SoapFormatter + : and then encoded with base64 encoding. + + mimetype: application/x-microsoft.net.object.bytearray.base64 + value : The object must be serialized into a byte array + : using a System.ComponentModel.TypeConverter + : and then encoded with base64 encoding. + --> + <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> + <xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> + <xsd:element name="root" msdata:IsDataSet="true"> + <xsd:complexType> + <xsd:choice maxOccurs="unbounded"> + <xsd:element name="metadata"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" /> + </xsd:sequence> + <xsd:attribute name="name" use="required" type="xsd:string" /> + <xsd:attribute name="type" type="xsd:string" /> + <xsd:attribute name="mimetype" type="xsd:string" /> + <xsd:attribute ref="xml:space" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="assembly"> + <xsd:complexType> + <xsd:attribute name="alias" type="xsd:string" /> + <xsd:attribute name="name" type="xsd:string" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="data"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> + <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> + </xsd:sequence> + <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> + <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> + <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> + <xsd:attribute ref="xml:space" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="resheader"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> + </xsd:sequence> + <xsd:attribute name="name" type="xsd:string" use="required" /> + </xsd:complexType> + </xsd:element> + </xsd:choice> + </xsd:complexType> + </xsd:element> + </xsd:schema> + <resheader name="resmimetype"> + <value>text/microsoft-resx</value> + </resheader> + <resheader name="version"> + <value>2.0</value> + </resheader> + <resheader name="reader"> + <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> + </resheader> + <resheader name="writer"> + <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> + </resheader> + <data name="RawDatagramSizeError" xml:space="preserve"> + <value>Wielkość datagramu powinna być pomiędzy 0 a 65507 bajtów</value> + </data> + <data name="RawStreamMessageSizeUnderflow" xml:space="preserve"> + <value>Maksymalna wielkość buforowanej wiadomośći powinna być większa niż 0 bajtów</value> + </data> +</root> +\ No newline at end of file diff --git a/NetSharp/NetSharp/Properties/Resources.resx b/NetSharp/NetSharp/Properties/Resources.resx @@ -0,0 +1,126 @@ +<?xml version="1.0" encoding="utf-8"?> +<root> + <!-- + Microsoft ResX Schema + + Version 2.0 + + The primary goals of this format is to allow a simple XML format + that is mostly human readable. The generation and parsing of the + various data types are done through the TypeConverter classes + associated with the data types. + + Example: + + ... ado.net/XML headers & schema ... + <resheader name="resmimetype">text/microsoft-resx</resheader> + <resheader name="version">2.0</resheader> + <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> + <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> + <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> + <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> + <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> + <value>[base64 mime encoded serialized .NET Framework object]</value> + </data> + <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> + <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> + <comment>This is a comment</comment> + </data> + + There are any number of "resheader" rows that contain simple + name/value pairs. + + Each data row contains a name, and value. The row also contains a + type or mimetype. Type corresponds to a .NET class that support + text/value conversion through the TypeConverter architecture. + Classes that don't support this are serialized and stored with the + mimetype set. + + The mimetype is used for serialized objects, and tells the + ResXResourceReader how to depersist the object. This is currently not + extensible. For a given mimetype the value must be set accordingly: + + Note - application/x-microsoft.net.object.binary.base64 is the format + that the ResXResourceWriter will generate, however the reader can + read any of the formats listed below. + + mimetype: application/x-microsoft.net.object.binary.base64 + value : The object must be serialized with + : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter + : and then encoded with base64 encoding. + + mimetype: application/x-microsoft.net.object.soap.base64 + value : The object must be serialized with + : System.Runtime.Serialization.Formatters.Soap.SoapFormatter + : and then encoded with base64 encoding. + + mimetype: application/x-microsoft.net.object.bytearray.base64 + value : The object must be serialized into a byte array + : using a System.ComponentModel.TypeConverter + : and then encoded with base64 encoding. + --> + <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> + <xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> + <xsd:element name="root" msdata:IsDataSet="true"> + <xsd:complexType> + <xsd:choice maxOccurs="unbounded"> + <xsd:element name="metadata"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" /> + </xsd:sequence> + <xsd:attribute name="name" use="required" type="xsd:string" /> + <xsd:attribute name="type" type="xsd:string" /> + <xsd:attribute name="mimetype" type="xsd:string" /> + <xsd:attribute ref="xml:space" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="assembly"> + <xsd:complexType> + <xsd:attribute name="alias" type="xsd:string" /> + <xsd:attribute name="name" type="xsd:string" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="data"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> + <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> + </xsd:sequence> + <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> + <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> + <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> + <xsd:attribute ref="xml:space" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="resheader"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> + </xsd:sequence> + <xsd:attribute name="name" type="xsd:string" use="required" /> + </xsd:complexType> + </xsd:element> + </xsd:choice> + </xsd:complexType> + </xsd:element> + </xsd:schema> + <resheader name="resmimetype"> + <value>text/microsoft-resx</value> + </resheader> + <resheader name="version"> + <value>2.0</value> + </resheader> + <resheader name="reader"> + <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> + </resheader> + <resheader name="writer"> + <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> + </resheader> + <data name="RawDatagramSizeError" xml:space="preserve"> + <value>The datagram size must be between 0 and 65507 bytes</value> + </data> + <data name="RawStreamMessageSizeUnderflow" xml:space="preserve"> + <value>The maximum pooled message size must be greater than 0 bytes</value> + </data> +</root> +\ No newline at end of file diff --git a/NetSharp/NetSharp/Raw/Datagram/RawDatagramNetworkReader.cs b/NetSharp/NetSharp/Raw/Datagram/RawDatagramNetworkReader.cs @@ -10,9 +10,7 @@ namespace NetSharp.Raw.Datagram public sealed class RawDatagramNetworkReader : RawNetworkReaderBase { - private const int MaxDatagramSize = ushort.MaxValue - 28; - - private readonly int messageSize; + private readonly int datagramSize; private readonly RawDatagramRequestHandler requestHandler; @@ -23,11 +21,10 @@ namespace NetSharp.Raw.Datagram { if (datagramSize <= 0 || MaxDatagramSize < datagramSize) { - throw new ArgumentOutOfRangeException(nameof(datagramSize), datagramSize, - $"The datagram size must be greater than 0 and less than {MaxDatagramSize}"); + throw new ArgumentOutOfRangeException(nameof(datagramSize), datagramSize, Properties.Resources.RawDatagramSizeError); } - messageSize = datagramSize; + this.datagramSize = datagramSize; this.requestHandler = requestHandler ?? DefaultRequestHandler; } @@ -45,14 +42,14 @@ namespace NetSharp.Raw.Datagram switch (args.SocketError) { case SocketError.Success: - byte[] responseBuffer = BufferPool.Rent(messageSize); + byte[] responseBuffer = BufferPool.Rent(datagramSize); bool responseExists = requestHandler(args.RemoteEndPoint, receiveBuffer, args.BytesTransferred, responseBuffer); BufferPool.Return(receiveBuffer, true); if (responseExists) { - args.SetBuffer(responseBuffer, 0, messageSize); + args.SetBuffer(responseBuffer, 0, datagramSize); SendTo(args); return; @@ -75,8 +72,8 @@ namespace NetSharp.Raw.Datagram [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ConfigureReceiveFrom(SocketAsyncEventArgs args) { - byte[] receiveBuffer = BufferPool.Rent(messageSize); - args.SetBuffer(receiveBuffer, 0, messageSize); + byte[] receiveBuffer = BufferPool.Rent(datagramSize); + args.SetBuffer(receiveBuffer, 0, datagramSize); } private void HandleIoCompleted(object sender, SocketAsyncEventArgs args) diff --git a/NetSharp/NetSharp/Raw/Datagram/RawDatagramNetworkWriter.cs b/NetSharp/NetSharp/Raw/Datagram/RawDatagramNetworkWriter.cs @@ -7,8 +7,6 @@ namespace NetSharp.Raw.Datagram { public sealed class RawDatagramNetworkWriter : RawNetworkWriterBase { - private const int MaxDatagramSize = ushort.MaxValue - 28; - private readonly int datagramSize; /// <inheritdoc /> @@ -17,8 +15,7 @@ namespace NetSharp.Raw.Datagram { if (datagramSize <= 0 || MaxDatagramSize < datagramSize) { - throw new ArgumentOutOfRangeException(nameof(datagramSize), datagramSize, - $"The datagram size must be greater than 0 and less than {MaxDatagramSize}"); + throw new ArgumentOutOfRangeException(nameof(datagramSize), datagramSize, Properties.Resources.RawDatagramSizeError); } this.datagramSize = datagramSize; diff --git a/NetSharp/NetSharp/Raw/RawNetworkConnectionBase.cs b/NetSharp/NetSharp/Raw/RawNetworkConnectionBase.cs @@ -21,6 +21,8 @@ namespace NetSharp.Raw // https://github.com/dotnet/coreclr/blob/master/src/System.Private.CoreLib/shared/System/Buffers/ConfigurableArrayPool.cs protected const int DefaultMaxPooledBufferSize = 1024 * 1024, DefaultMaxPooledBuffersPerBucket = 50; + protected const int MaxDatagramSize = ushort.MaxValue - 28; // 65535 - 28 = 65507 + protected RawNetworkConnectionBase(ref Socket rawConnection, EndPoint defaultEndPoint, int maxPooledBufferSize, int pooledBuffersPerBucket = 50, uint preallocatedStateObjects = 0) { diff --git a/NetSharp/NetSharp/Raw/Stream/RawStreamNetworkReader.cs b/NetSharp/NetSharp/Raw/Stream/RawStreamNetworkReader.cs @@ -20,8 +20,7 @@ namespace NetSharp.Raw.Stream { if (maxPooledMessageSize <= 0) { - throw new ArgumentOutOfRangeException(nameof(maxPooledMessageSize), maxPooledMessageSize, - "The maximum message size must be greater than 0"); + throw new ArgumentOutOfRangeException(nameof(maxPooledMessageSize), maxPooledMessageSize, Properties.Resources.RawStreamMessageSizeUnderflow); } RequestHandler = requestHandler ?? DefaultRequestHandler; diff --git a/NetSharp/NetSharp/Raw/Stream/RawStreamNetworkWriter.cs b/NetSharp/NetSharp/Raw/Stream/RawStreamNetworkWriter.cs @@ -15,8 +15,7 @@ namespace NetSharp.Raw.Stream { if (maxPooledMessageSize <= 0) { - throw new ArgumentOutOfRangeException(nameof(maxPooledMessageSize), maxPooledMessageSize, - "The message size must be greater than 0"); + throw new ArgumentOutOfRangeException(nameof(maxPooledMessageSize), maxPooledMessageSize, Properties.Resources.RawStreamMessageSizeUnderflow); } } diff --git a/NetSharp/NetSharpExamples/Examples/Datagram Network Connection Examples/DatagramNetworkReaderExample.cs b/NetSharp/NetSharpExamples/Examples/Datagram Network Connection Examples/DatagramNetworkReaderExample.cs @@ -20,14 +20,15 @@ namespace NetSharpExamples.Examples.Datagram_Network_Connection_Examples private static bool RequestHandler(EndPoint remoteEndPoint, in ReadOnlyMemory<byte> requestBuffer, int receivedRequestBytes, in Memory<byte> responseBuffer) { - requestBuffer.CopyTo(responseBuffer); - lock (typeof(Console)) { - Console.WriteLine($"Received {receivedRequestBytes} bytes from {remoteEndPoint}! Echoing back..."); + string request = ServerEncoding.GetString(requestBuffer.Span).Trim('\0'); + + Console.WriteLine($"[Server] Received request \'{request}\' ({receivedRequestBytes} bytes) from {remoteEndPoint}"); + Console.WriteLine($"[Server] Sending response \'{request}\' ({receivedRequestBytes} bytes) to {remoteEndPoint}"); } - return true; + return requestBuffer.TryCopyTo(responseBuffer); } /// <inheritdoc /> diff --git a/NetSharp/NetSharpExamples/Examples/Datagram Network Connection Examples/DatagramNetworkWriterAsyncExample.cs b/NetSharp/NetSharpExamples/Examples/Datagram Network Connection Examples/DatagramNetworkWriterAsyncExample.cs @@ -36,7 +36,14 @@ namespace NetSharpExamples.Examples.Datagram_Network_Connection_Examples { while (true) { - //TODO add user input + Console.Write("Input to send to server: "); + string userInput = Console.ReadLine(); + + if (!ServerEncoding.GetBytes(userInput).AsMemory().TryCopyTo(transmissionBuffer)) + { + Console.WriteLine("Given input is too large. Please try again!"); + continue; + } int sent = await writer.WriteAsync(remoteEndPoint, transmissionBuffer); @@ -45,11 +52,14 @@ namespace NetSharpExamples.Examples.Datagram_Network_Connection_Examples Console.WriteLine($"Sent {sent} bytes to {remoteEndPoint}!"); } + Array.Clear(transmissionBuffer, 0, transmissionBuffer.Length); + int received = await writer.ReadAsync(remoteEndPoint, transmissionBuffer); lock (typeof(Console)) { Console.WriteLine($"Received {received} bytes from {remoteEndPoint}!"); + Console.WriteLine(ServerEncoding.GetString(transmissionBuffer)); } } } diff --git a/NetSharp/NetSharpExamples/Examples/Datagram Network Connection Examples/DatagramNetworkWriterSyncExample.cs b/NetSharp/NetSharpExamples/Examples/Datagram Network Connection Examples/DatagramNetworkWriterSyncExample.cs @@ -36,7 +36,14 @@ namespace NetSharpExamples.Examples.Datagram_Network_Connection_Examples { while (true) { - // TODO add user input + Console.Write("Input to send to server: "); + string userInput = Console.ReadLine(); + + if (!ServerEncoding.GetBytes(userInput).AsMemory().TryCopyTo(transmissionBuffer)) + { + Console.WriteLine("Given input is too large. Please try again!"); + continue; + } int sent = writer.Write(remoteEndPoint, transmissionBuffer); @@ -45,11 +52,14 @@ namespace NetSharpExamples.Examples.Datagram_Network_Connection_Examples Console.WriteLine($"Sent {sent} bytes to {remoteEndPoint}!"); } + Array.Clear(transmissionBuffer, 0, transmissionBuffer.Length); + int received = writer.Read(ref remoteEndPoint, transmissionBuffer); lock (typeof(Console)) { Console.WriteLine($"Received {received} bytes from {remoteEndPoint}!"); + Console.WriteLine(ServerEncoding.GetString(transmissionBuffer)); } } } @@ -58,8 +68,6 @@ namespace NetSharpExamples.Examples.Datagram_Network_Connection_Examples rawSocket.Close(); rawSocket.Dispose(); } - - return Task.CompletedTask; } } } \ No newline at end of file diff --git a/NetSharp/NetSharpExamples/Examples/Stream Network Connection Examples/RawStreamChatServer.cs b/NetSharp/NetSharpExamples/Examples/Stream Network Connection Examples/RawStreamChatServer.cs @@ -74,10 +74,13 @@ namespace NetSharpExamples.Examples.Stream_Network_Connection_Examples private static bool ServerPacketHandler(EndPoint remoteEndPoint, in ReadOnlyMemory<byte> requestBuffer, int receivedRequestBytes, in Memory<byte> responseBuffer) { - string request = ServerEncoding.GetString(requestBuffer.Span).Trim('\0'); + lock (typeof(Console)) + { + string request = ServerEncoding.GetString(requestBuffer.Span).Trim('\0'); - Console.WriteLine($"[Server] Received request \'{request}\' from {remoteEndPoint}"); - Console.WriteLine($"[Server] Sending response \'{request}\' to {remoteEndPoint}"); + Console.WriteLine($"[Server] Received request \'{request}\' ({receivedRequestBytes} bytes) from {remoteEndPoint}"); + Console.WriteLine($"[Server] Sending response \'{request}\' ({receivedRequestBytes} bytes) to {remoteEndPoint}"); + } return requestBuffer.TryCopyTo(responseBuffer); } @@ -101,10 +104,6 @@ namespace NetSharpExamples.Examples.Stream_Network_Connection_Examples while (true) { } - - server.Shutdown(); - - return Task.CompletedTask; } public async Task RunAsync() diff --git a/NetSharp/NetSharpExamples/Examples/Stream Network Connection Examples/StreamNetworkReaderExample.cs b/NetSharp/NetSharpExamples/Examples/Stream Network Connection Examples/StreamNetworkReaderExample.cs @@ -20,14 +20,15 @@ namespace NetSharpExamples.Examples.Stream_Network_Connection_Examples private static bool RequestHandler(EndPoint remoteEndPoint, in ReadOnlyMemory<byte> requestBuffer, int receivedRequestBytes, in Memory<byte> responseBuffer) { - requestBuffer.CopyTo(responseBuffer); - lock (typeof(Console)) { - Console.WriteLine($"Received {receivedRequestBytes} bytes from {remoteEndPoint}! Echoing back..."); + string request = ServerEncoding.GetString(requestBuffer.Span).Trim('\0'); + + Console.WriteLine($"[Server] Received request \'{request}\' ({receivedRequestBytes} bytes) from {remoteEndPoint}"); + Console.WriteLine($"[Server] Sending response \'{request}\' ({receivedRequestBytes} bytes) to {remoteEndPoint}"); } - return true; + return requestBuffer.TryCopyTo(responseBuffer); } /// <inheritdoc /> diff --git a/NetSharp/NetSharpExamples/Examples/Stream Network Connection Examples/StreamNetworkWriterAsyncExample.cs b/NetSharp/NetSharpExamples/Examples/Stream Network Connection Examples/StreamNetworkWriterAsyncExample.cs @@ -37,7 +37,14 @@ namespace NetSharpExamples.Examples.Stream_Network_Connection_Examples { while (true) { - // TODO add user input + Console.Write("Input to send to server: "); + string userInput = Console.ReadLine(); + + if (!ServerEncoding.GetBytes(userInput).AsMemory().TryCopyTo(transmissionBuffer)) + { + Console.WriteLine("Given input is too large. Please try again!"); + continue; + } int sent = await writer.WriteAsync(remoteEndPoint, transmissionBuffer); @@ -46,11 +53,14 @@ namespace NetSharpExamples.Examples.Stream_Network_Connection_Examples Console.WriteLine($"Sent {sent} bytes to {remoteEndPoint}!"); } + Array.Clear(transmissionBuffer, 0, transmissionBuffer.Length); + int received = await writer.ReadAsync(remoteEndPoint, transmissionBuffer); lock (typeof(Console)) { Console.WriteLine($"Received {received} bytes from {remoteEndPoint}!"); + Console.WriteLine(ServerEncoding.GetString(transmissionBuffer)); } } } diff --git a/NetSharp/NetSharpExamples/Examples/Stream Network Connection Examples/StreamNetworkWriterSyncExample.cs b/NetSharp/NetSharpExamples/Examples/Stream Network Connection Examples/StreamNetworkWriterSyncExample.cs @@ -37,7 +37,14 @@ namespace NetSharpExamples.Examples.Stream_Network_Connection_Examples { while (true) { - // TODO add user input + Console.Write("Input to send to server: "); + string userInput = Console.ReadLine(); + + if (!ServerEncoding.GetBytes(userInput).AsMemory().TryCopyTo(transmissionBuffer)) + { + Console.WriteLine("Given input is too large. Please try again!"); + continue; + } int sent = writer.Write(remoteEndPoint, transmissionBuffer); @@ -46,11 +53,14 @@ namespace NetSharpExamples.Examples.Stream_Network_Connection_Examples Console.WriteLine($"Sent {sent} bytes to {remoteEndPoint}!"); } + Array.Clear(transmissionBuffer, 0, transmissionBuffer.Length); + int received = writer.Read(ref remoteEndPoint, transmissionBuffer); lock (typeof(Console)) { Console.WriteLine($"Received {received} bytes from {remoteEndPoint}!"); + Console.WriteLine(ServerEncoding.GetString(transmissionBuffer)); } } } diff --git a/NetSharp/NetSharpExamples/Program.cs b/NetSharp/NetSharpExamples/Program.cs @@ -2,9 +2,12 @@ using System.Collections.Generic; using System.Net; using System.Reflection; +using System.Resources; using System.Text; using System.Threading.Tasks; +[assembly: NeutralResourcesLanguage("en")] + namespace NetSharpExamples { internal class Program @@ -97,6 +100,10 @@ namespace NetSharpExamples { Console.WriteLine("Invalid option selected. Please try again!"); } + catch (Exception ex) + { + Console.WriteLine(ex); + } } Console.WriteLine();