├── RxSockets ├── worm64.png ├── Utilities │ ├── Utilities.cs │ ├── AsyncEmptyDisposable.cs │ ├── NullRxSockets.cs │ ├── SocketDisposer.cs │ ├── SocketReceiver.cs │ └── SocketAcceptor.cs ├── Extensions │ ├── BackgroundThreadScheduler.cs │ ├── LoggerExtensions.cs │ ├── StringArrayExtensions.cs │ ├── RxSocketsExtensions.cs │ ├── StringExtensions.cs │ └── LengthPrefixExtensions.cs ├── Assembly.cs ├── RxSockets.csproj ├── RxSocketClient.cs └── RxSocketServer.cs ├── RxSockets.Tests ├── TestBase.cs ├── Assembly.cs ├── Extensions │ ├── ToByteArrayWithLengthPrefixTest.cs │ ├── ToArraysFromBytesWithLengthPrefix.cs │ ├── StringExtensionsTests.cs │ └── ToStringArraysTest.cs ├── Utility │ ├── Socket_Acceptor_Tests.cs │ ├── Socket_Connect_Tests.cs │ ├── Socket_Disposer_Tests.cs │ └── Socket_Reader_Tests.cs ├── RxSockets.Tests.csproj ├── TestUtilities.cs ├── Tests │ ├── ServerTests.cs │ ├── PerformanceTests.cs │ ├── ClientTests.cs │ └── ClientServerTest.cs ├── ~scratch │ └── ClientServerTest.cs └── Examples │ ├── SimpleExample.cs │ └── Examples.cs ├── appveyor.yml ├── RxSockets.sln ├── .gitattributes ├── README.md ├── .gitignore └── LICENSE /RxSockets/worm64.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dshe/RxSockets/HEAD/RxSockets/worm64.png -------------------------------------------------------------------------------- /RxSockets/Utilities/Utilities.cs: -------------------------------------------------------------------------------- 1 | namespace RxSockets; 2 | 3 | internal static class Utilities 4 | { 5 | internal static IPEndPoint CreateIPEndPointOnPort(int port) => new(IPAddress.Loopback, port); 6 | 7 | internal static Socket CreateSocket() => new(SocketType.Stream, ProtocolType.Tcp) { NoDelay = true }; 8 | } 9 | -------------------------------------------------------------------------------- /RxSockets/Utilities/AsyncEmptyDisposable.cs: -------------------------------------------------------------------------------- 1 | namespace RxSockets; 2 | 3 | public sealed class AsyncEmptyDisposable : IAsyncDisposable 4 | { 5 | public static IAsyncDisposable Instance { get; } = new AsyncEmptyDisposable(); 6 | private AsyncEmptyDisposable() { } 7 | public ValueTask DisposeAsync() => ValueTask.CompletedTask; 8 | } 9 | -------------------------------------------------------------------------------- /RxSockets/Extensions/BackgroundThreadScheduler.cs: -------------------------------------------------------------------------------- 1 | using System.Reactive.Concurrency; 2 | namespace RxSockets; 3 | 4 | public static partial class Extension 5 | { 6 | // Usage: IObservable.SubscribeOn(NewThreadScheduler.BackgroundThread("SubscriberThread")); 7 | public static NewThreadScheduler BackgroundThread(this NewThreadScheduler _, string name = "NewBackgroundThread") 8 | { 9 | return new NewThreadScheduler(threadStart => new Thread(threadStart) 10 | { 11 | Name = name, 12 | IsBackground = true 13 | }); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /RxSockets.Tests/TestBase.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging; 2 | namespace RxSockets.Tests; 3 | 4 | public abstract class TestBase 5 | { 6 | protected readonly Action Write; 7 | protected readonly ILoggerFactory LogFactory; 8 | protected readonly ILogger Logger; 9 | 10 | protected TestBase(ITestOutputHelper output) 11 | { 12 | Write = output.WriteLine; 13 | 14 | LogFactory = LoggerFactory.Create(builder => builder 15 | .AddMXLogger(Write) 16 | .SetMinimumLevel(LogLevel.Debug)); 17 | 18 | Logger = LogFactory.CreateLogger("Test"); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /RxSockets.Tests/Assembly.cs: -------------------------------------------------------------------------------- 1 | global using System; 2 | global using System.Linq; 3 | global using System.Net; 4 | global using System.Net.Sockets; 5 | global using System.Reactive.Linq; 6 | global using Xunit; 7 | global using Xunit.Abstractions; 8 | global using RxSockets; 9 | using System.Diagnostics.CodeAnalysis; 10 | 11 | [assembly: SuppressMessage("Usage", "IDE0130:Namespace does not match folder structure,")] 12 | [assembly: SuppressMessage("Usage", "CA2254:The logging message template should not vary between calls")] 13 | [assembly: SuppressMessage("Usage", "CA1861:Prefer static readonbly fields over constant arrays passed as arguments")] 14 | -------------------------------------------------------------------------------- /RxSockets/Assembly.cs: -------------------------------------------------------------------------------- 1 | global using System; 2 | global using System.Linq; 3 | global using System.Collections.Generic; 4 | global using System.Net; 5 | global using System.Net.Sockets; 6 | global using System.Threading; 7 | global using System.Threading.Tasks; 8 | global using Microsoft.Extensions.Logging; 9 | using System.Runtime.CompilerServices; 10 | using System.Diagnostics.CodeAnalysis; 11 | 12 | [assembly: CLSCompliant(true)] 13 | [assembly: InternalsVisibleTo("RxSockets.Tests")] 14 | 15 | [assembly: SuppressMessage("Usage", "CA1848:Use the LoggerMessage delegates")] 16 | [assembly: SuppressMessage("Usage", "IDE0130:Namespace does not match folder structure,")] 17 | -------------------------------------------------------------------------------- /RxSockets.Tests/Extensions/ToByteArrayWithLengthPrefixTest.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | namespace RxSockets.Tests; 3 | 4 | public class ToByteArrayWithLengthPrefixTest 5 | { 6 | [Theory] 7 | [InlineData(new byte[] { 0, 0, 0, 0 }, new string[] { })] 8 | [InlineData(new byte[] { 0, 0, 0, 1, 0 }, new[] { "" })] 9 | [InlineData(new byte[] { 0, 0, 0, 2, 0, 0 }, new[] { "\0" })] 10 | [InlineData(new byte[] { 0, 0, 0, 2, 65, 0 }, new[] { "A" })] 11 | [InlineData(new byte[] { 0, 0, 0, 4, 65, 0, 66, 0 }, new[] { "A", "B" })] 12 | public void T01(byte[] encoded, IEnumerable strings) 13 | { 14 | Assert.Equal(encoded, strings.ToArray().ToByteArray().ToByteArrayWithLengthPrefix()); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /RxSockets/Extensions/LoggerExtensions.cs: -------------------------------------------------------------------------------- 1 | namespace RxSockets; 2 | 3 | public static partial class Extension 4 | { 5 | [LoggerMessage(EventId = 1, EventName = "SendBytes", Level = LogLevel.Trace, Message = "Send: {Name} on {LocalEndPoint} sending {Bytes} bytes to {RemoteEndPoint}.")] 6 | internal static partial void LogSend(this ILogger logger, string name, EndPoint? localEndPoint, int bytes, EndPoint? remoteEndPoint); 7 | 8 | [LoggerMessage(EventId = 2, EventName = "ReceiveBytes", Level = LogLevel.Trace, Message = "Receive: {Name} on {LocalEndPoint} received {Bytes} bytes from {RemoteEndPoint}.")] 9 | internal static partial void LogReceive(this ILogger logger, string name, EndPoint? localEndPoint, int bytes, EndPoint? remoteEndPoint); 10 | } 11 | 12 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | environment: 2 | base_version: '7.0.4' 3 | version_suffix: '' 4 | version: $(base_version).{build} 5 | image: Visual Studio 2022 6 | configuration: Release 7 | dotnet_csproj: 8 | patch: true 9 | file: '**\*.csproj' 10 | version: '$(base_version)$(version_suffix)' 11 | package_version: '$(base_version)$(version_suffix)' 12 | assembly_version: '{version}' 13 | file_version: '{version}' 14 | informational_version: '$(base_version)$(version_suffix)' 15 | before_build: 16 | - ps: dotnet restore 17 | after_build: 18 | - ps: dotnet pack -c release 19 | build: 20 | verbosity: minimal 21 | publish_nuget: true 22 | test_script: 23 | - ps: dotnet test .\RxSockets.Tests\RxSockets.Tests.csproj 24 | nuget: 25 | account_feed: false 26 | project_feed: true 27 | disable_publish_on_pr: true 28 | artifacts: 29 | - path: '**\*.nupkg' 30 | -------------------------------------------------------------------------------- /RxSockets.Tests/Utility/Socket_Acceptor_Tests.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging; 2 | using System.Threading.Tasks; 3 | namespace RxSockets.Tests; 4 | 5 | public class Socket_Acceptor_Tests(ITestOutputHelper output) : TestBase(output) 6 | { 7 | [Fact] 8 | public async Task T00_Success() 9 | { 10 | EndPoint endPoint = Utilities.CreateIPEndPointOnPort(0); 11 | Socket serverSocket = Utilities.CreateSocket(); 12 | serverSocket.Bind(endPoint); 13 | serverSocket.Listen(10); 14 | endPoint = serverSocket.LocalEndPoint ?? throw new InvalidOperationException(); 15 | 16 | Task task = Task.Run(async () => 17 | { 18 | SocketAcceptor acceptor = new(serverSocket, LogFactory.CreateLogger(), default); 19 | await foreach (IRxSocketClient cli in acceptor.CreateAcceptAllAsync(default)) 20 | { 21 | Logger.LogDebug("client"); 22 | } 23 | }); 24 | 25 | IRxSocketClient client = await endPoint.CreateRxSocketClientAsync(LogFactory, default); 26 | Assert.True(client.Connected); 27 | 28 | await Task.Delay(100); 29 | 30 | await client.DisposeAsync(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /RxSockets.Tests/RxSockets.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | false 7 | Library 8 | en 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | runtime; build; native; contentfiles; analyzers; buildtransitive 17 | all 18 | 19 | 20 | 21 | runtime; build; native; contentfiles; analyzers; buildtransitive 22 | all 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /RxSockets/Utilities/NullRxSockets.cs: -------------------------------------------------------------------------------- 1 | using System.Reactive.Linq; 2 | namespace RxSockets; 3 | 4 | public sealed class NullRxSocketClient : IRxSocketClient 5 | { 6 | public static IRxSocketClient Instance { get; } = new NullRxSocketClient(); 7 | private NullRxSocketClient() { } 8 | public EndPoint RemoteEndPoint => throw new InvalidOperationException(); 9 | public bool Connected { get; } 10 | public int Send(ReadOnlySpan buffer) => throw new InvalidOperationException(); 11 | public IObservable ReceiveObservable => Observable.Empty(); 12 | public IAsyncEnumerable ReceiveAllAsync => throw new InvalidOperationException(); 13 | public ValueTask DisposeAsync() => ValueTask.CompletedTask; 14 | } 15 | 16 | public sealed class NullRxSocketServer : IRxSocketServer 17 | { 18 | public static IRxSocketServer Instance { get; } = new NullRxSocketServer(); 19 | private NullRxSocketServer() { } 20 | public EndPoint LocalEndPoint => throw new InvalidOperationException(); 21 | public IObservable AcceptObservable => Observable.Empty(); 22 | public IAsyncEnumerable AcceptAllAsync => throw new InvalidOperationException(); 23 | public ValueTask DisposeAsync() => ValueTask.CompletedTask; 24 | } 25 | -------------------------------------------------------------------------------- /RxSockets.Tests/Extensions/ToArraysFromBytesWithLengthPrefix.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using System.Threading.Tasks; 3 | namespace RxSockets.Tests; 4 | 5 | public class ToArraysFromBytesWithLengthPrefix 6 | { 7 | [Fact] 8 | public async Task T01() 9 | { 10 | await Assert.ThrowsAsync(async () => 11 | await (new byte[] { 0, 0, 0, 0, 0 }).ToObservable().ToArraysFromBytesWithLengthPrefix().FirstAsync()); 12 | } 13 | 14 | [Theory] 15 | [InlineData(new byte[] { 0 }, new byte[] { 0, 0, 0, 1, 0 })] 16 | [InlineData(new byte[] { 65, 0 }, new byte[] { 0, 0, 0, 2, 65, 0 })] 17 | [InlineData(new byte[] { 65, 0, 66, 0 }, new byte[] { 0, 0, 0, 4, 65, 0, 66, 0 })] 18 | public async Task T02(byte[] result, byte[] bytes) 19 | { 20 | Assert.Equal(result, bytes.ToArraysFromBytesWithLengthPrefix().First()); 21 | Assert.Equal(result, await bytes.ToObservable().ToArraysFromBytesWithLengthPrefix()); 22 | } 23 | 24 | [Fact] 25 | public void T03() 26 | { 27 | Assert.Throws(() => Extension.ToArraysFromBytesWithLengthPrefix([]).First()); 28 | Assert.Throws(() => Extension.ToArraysFromBytesWithLengthPrefix([65]).First()); 29 | Assert.Throws(() => Extension.ToArraysFromBytesWithLengthPrefix([65, 0, 65]).First()); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /RxSockets/RxSockets.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | Apache-2.0 7 | https://github.com/dshe/RxSockets 8 | worm64.png 9 | sockets reactive-extensions reactive observable async-enumerable linq 10 | A minimal reactive socket implementation. 11 | DavidS 12 | 7.0.4 13 | 7.0.4 14 | 7.0.4 15 | Library 16 | https://github.com/dshe/RxSockets 17 | github 18 | embedded 19 | true 20 | False 21 | All 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /RxSockets/Extensions/StringArrayExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using System.Reactive.Linq; 3 | using System.Text; 4 | namespace RxSockets; 5 | 6 | public static partial class Extension 7 | { 8 | /// 9 | /// Transform a sequence of byte arrays into a sequence of string arrays. 10 | /// 11 | public static IEnumerable ToStringArrays(this IEnumerable source) => 12 | source.Select(buffer => buffer.ToStringArray()); 13 | 14 | /// 15 | /// Transform a sequence of byte arrays into a sequence of string arrays. 16 | /// 17 | public static IAsyncEnumerable ToStringArrays(this IAsyncEnumerable source) => 18 | source.Select(bytes => bytes.ToStringArray()); 19 | 20 | /// 21 | /// Transform a sequence of byte arrays into a sequence of string arrays. 22 | /// 23 | public static IObservable ToStringArrays(this IObservable source) => 24 | source.Select(buffer => buffer.ToStringArray()); 25 | 26 | /// 27 | /// Transform a byte array into an array of strings. 28 | /// 29 | private static string[] ToStringArray(this byte[] buffer) 30 | { 31 | int length = buffer.Length; 32 | if (length == 0 || buffer[length - 1] != 0) 33 | throw new InvalidDataException("ToStringArray: no termination."); 34 | return Encoding.UTF8.GetString(buffer, 0, length - 1).Split('\0'); 35 | } 36 | } 37 | 38 | -------------------------------------------------------------------------------- /RxSockets.Tests/TestUtilities.cs: -------------------------------------------------------------------------------- 1 | using System.Net.NetworkInformation; 2 | using System.Security.Cryptography; 3 | namespace RxSockets.Tests; 4 | 5 | public static class TestUtilities 6 | { 7 | private static readonly RandomNumberGenerator RandomNumberGenerator = RandomNumberGenerator.Create(); 8 | private static readonly object Locker = new(); 9 | 10 | public static IPEndPoint GetEndPointOnRandomLoopbackPort() => 11 | new(IPAddress.Loopback, GetRandomAvailablePort()); 12 | 13 | private static int GetRandomAvailablePort() 14 | { 15 | lock (Locker) 16 | { 17 | while (true) 18 | { 19 | // IANA officially recommends 49152 - 65535 for the Ephemeral Ports. 20 | int port = RandomInt(49152, 65535); 21 | if (!IsPortUsed(port)) 22 | return port; 23 | } 24 | } 25 | } 26 | 27 | private static bool IsPortUsed(int port) => 28 | IPGlobalProperties 29 | .GetIPGlobalProperties() 30 | .GetActiveTcpListeners() 31 | .Any(ep => ep.Port == port); 32 | 33 | private static int RandomInt(int min, int max) 34 | { 35 | byte[] buffer = GetRandomBytes(4); 36 | int result = BitConverter.ToInt32(buffer, 0); 37 | return new Random(result).Next(min, max); 38 | } 39 | 40 | private static byte[] GetRandomBytes(int bytes) 41 | { 42 | byte[] buffer = new byte[bytes]; 43 | RandomNumberGenerator.GetBytes(buffer, 0, bytes); 44 | return buffer; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /RxSockets.Tests/Tests/ServerTests.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | namespace RxSockets.Tests; 3 | 4 | public class ServerTest(ITestOutputHelper output) : TestBase(output) 5 | { 6 | [Fact] 7 | public void T01_Invalid_EndPoint() 8 | { 9 | IPEndPoint endPoint = new(IPAddress.Parse("111.111.111.111"), 1111); 10 | Assert.Throws(() => RxSocketServer.Create(endPoint, LogFactory)); 11 | } 12 | 13 | [Fact] 14 | public async Task T02_Accept_Success() 15 | { 16 | IRxSocketServer server = RxSocketServer.Create(LogFactory); 17 | EndPoint endPoint = server.LocalEndPoint; 18 | 19 | ValueTask acceptTask = server.AcceptAllAsync.FirstAsync(); 20 | 21 | Socket clientSocket = Utilities.CreateSocket(); 22 | await clientSocket.ConnectAsync(endPoint); 23 | 24 | IRxSocketClient acceptedSocket = await acceptTask; 25 | 26 | Assert.True(clientSocket.Connected && acceptedSocket.Connected); 27 | 28 | await clientSocket.DisconnectAsync(false); 29 | await server.DisposeAsync(); 30 | } 31 | 32 | [Fact] 33 | public async Task T03_Disconnect_Before_Accept() 34 | { 35 | IRxSocketServer server = RxSocketServer.Create(LogFactory); 36 | await server.DisposeAsync(); 37 | await Assert.ThrowsAsync(async () => await server.AcceptAllAsync.FirstAsync()); 38 | } 39 | 40 | [Fact] 41 | public async Task T04_Disconnect_While_Accept() 42 | { 43 | IRxSocketServer server = RxSocketServer.Create(LogFactory); 44 | ValueTask acceptTask = server.AcceptAllAsync.FirstAsync(); 45 | await server.DisposeAsync(); 46 | await Assert.ThrowsAsync(async () => await acceptTask); 47 | } 48 | } 49 | 50 | -------------------------------------------------------------------------------- /RxSockets/RxSocketClient.cs: -------------------------------------------------------------------------------- 1 | namespace RxSockets; 2 | 3 | public interface IRxSocketClient : IAsyncDisposable 4 | { 5 | EndPoint RemoteEndPoint { get; } 6 | bool Connected { get; } 7 | int Send(ReadOnlySpan buffer); 8 | IObservable ReceiveObservable { get; } 9 | IAsyncEnumerable ReceiveAllAsync { get; } 10 | } 11 | 12 | public sealed class RxSocketClient : IRxSocketClient 13 | { 14 | private readonly string Name; 15 | private readonly ILogger Logger; 16 | private readonly CancellationTokenSource DisposalCts = new(); 17 | private readonly Socket Socket; 18 | private readonly SocketDisposer Disposer; 19 | public EndPoint RemoteEndPoint { get; } 20 | public bool Connected => 21 | !((Socket.Poll(1000, SelectMode.SelectRead) && Socket.Available == 0) || !Socket.Connected); 22 | public IObservable ReceiveObservable { get; } 23 | public IAsyncEnumerable ReceiveAllAsync { get; } 24 | 25 | internal RxSocketClient(Socket socket, ILogger logger, string name) 26 | { 27 | Socket = socket; 28 | Logger = logger; 29 | Name = name; 30 | RemoteEndPoint = Socket.RemoteEndPoint ?? throw new InvalidOperationException(); 31 | Disposer = new SocketDisposer(socket, Name, Logger, DisposalCts); 32 | SocketReceiver receiver = new(socket, Name, Logger, DisposalCts.Token); 33 | ReceiveObservable = receiver.CreateReceiveObservable(); 34 | ReceiveAllAsync = receiver.ReceiveAllAsync(); 35 | } 36 | 37 | public int Send(ReadOnlySpan buffer) 38 | { 39 | Logger.LogSend(Name, Socket.LocalEndPoint, buffer.Length, Socket.RemoteEndPoint); 40 | return Socket.Send(buffer); 41 | } 42 | 43 | public async ValueTask DisposeAsync() 44 | { 45 | await Disposer.DisposeAsync().ConfigureAwait(false); 46 | DisposalCts.Dispose(); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /RxSockets.Tests/~scratch/ClientServerTest.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging; 2 | using Microsoft.VisualStudio.TestPlatform.ObjectModel; 3 | using System.Diagnostics; 4 | using System.Reactive.Concurrency; 5 | using System.Reactive.Disposables; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | namespace RxSockets.Tests; 9 | 10 | public class SomeTest(ITestOutputHelper output) : TestBase(output) 11 | { 12 | [Fact] 13 | public async Task Test1() 14 | { 15 | Write(Environment.CurrentManagedThreadId + ": start " + Thread.CurrentThread.Name); 16 | 17 | IObservable observable = Observable.Create(observer => 18 | { 19 | return NewThreadScheduler.Default.ScheduleLongRunning((ct) => 20 | { 21 | //ct.IsDisposed 22 | //ct. 23 | Write(Environment.CurrentManagedThreadId + ": " + Thread.CurrentThread.Name); 24 | //Thread.CurrentThread.Name = "Producer"; 25 | //Write("Producing"); 26 | Write(Environment.CurrentManagedThreadId + ": producing"); 27 | observer.OnNext(OnNext("a")); 28 | observer.OnNext(OnNext("b")); 29 | observer.OnNext(OnNext("c")); 30 | observer.OnCompleted(); 31 | }); 32 | //return Disposable.Empty; 33 | 34 | }); 35 | 36 | observable.ObserveOn(NewThreadScheduler.Default.BackgroundThread("SubscriberThread")).Subscribe(msg => 37 | //observable.SubscribeOn(NewThreadScheduler.Default.BackgroundThread("SubscriberThread")).Subscribe(msg => 38 | //observable.Subscribe(msg => 39 | { 40 | Write(Environment.CurrentManagedThreadId + ": " + msg + " " + Thread.CurrentThread.Name); 41 | }); 42 | 43 | await Task.Delay(1000); 44 | } 45 | 46 | private string OnNext(string str) 47 | { 48 | Write(Environment.CurrentManagedThreadId + ": observing " + str); 49 | return str; 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /RxSockets.Tests/Extensions/StringExtensionsTests.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.IO; 3 | using System.Threading.Tasks; 4 | namespace RxSockets.Tests; 5 | 6 | public class StringExtensionsTests 7 | { 8 | [Theory] 9 | [InlineData(new byte[] { 0 }, "")] 10 | [InlineData(new byte[] { 0, 0 }, "\0")] 11 | [InlineData(new byte[] { 65, 0 }, "A")] 12 | [InlineData(new byte[] { 65, 66, 0 }, "AB")] 13 | public void T01_ToByteArray(byte[] encoded, string str) => 14 | Assert.Equal(encoded, str.ToByteArray()); 15 | 16 | [Fact] 17 | public async Task T02_To_Strings() 18 | { 19 | await Assert.ThrowsAsync(async () => 20 | #pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. 21 | await ((byte[]?)null).ToObservable().ToStrings().ToList()); // should have warning? 22 | #pragma warning restore CS8625 23 | 24 | // no termination 25 | Assert.Throws(() => "A"u8.ToArray().ToStrings().ToList()); 26 | await Assert.ThrowsAsync(async () => 27 | await "A"u8.ToArray().ToObservable().ToStrings().ToList()); 28 | 29 | IObservable observable = Observable.Throw(new ArithmeticException()).ToStrings(); 30 | await Assert.ThrowsAsync(async () => await observable); 31 | } 32 | 33 | [Theory] 34 | [InlineData(new string[] { }, new byte[] { })] 35 | [InlineData(new[] { "" }, new byte[] { 0 })] 36 | [InlineData(new[] { "A" }, new byte[] { 65, 0 })] 37 | [InlineData(new[] { "AB" }, new byte[] { 65, 66, 0 })] 38 | [InlineData(new[] { "", "" }, new byte[] { 0, 0 })] 39 | [InlineData(new[] { "A", "B" }, new byte[] { 65, 0, 66, 0 })] 40 | public async Task T03_To_Strings(IEnumerable strings, byte[] bytes) 41 | { 42 | Assert.Equal(strings, bytes.ToStrings().ToList()); 43 | Assert.Equal(strings, await bytes.ToObservable().ToStrings().ToList()); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /RxSockets.Tests/Utility/Socket_Connect_Tests.cs: -------------------------------------------------------------------------------- 1 | using System.Threading; 2 | using System.Threading.Tasks; 3 | namespace RxSockets.Tests; 4 | 5 | public class SocketConnectTests(ITestOutputHelper output) : TestBase(output) 6 | { 7 | [Fact] 8 | public async Task T00_Success() 9 | { 10 | EndPoint endPoint = Utilities.CreateIPEndPointOnPort(0); 11 | Socket serverSocket = Utilities.CreateSocket(); 12 | serverSocket.Bind(endPoint); 13 | serverSocket.Listen(10); 14 | EndPoint actualServerEndpoint = serverSocket.LocalEndPoint ?? throw new InvalidOperationException(); 15 | 16 | IRxSocketClient client = await actualServerEndpoint.CreateRxSocketClientAsync(Logger); 17 | Assert.True(client.Connected); 18 | 19 | await client.DisposeAsync(); 20 | serverSocket.Dispose(); 21 | } 22 | 23 | [Fact] 24 | public async Task T01_Connection_Refused_Test() 25 | { 26 | IPEndPoint endPoint = TestUtilities.GetEndPointOnRandomLoopbackPort(); 27 | SocketException e = await Assert.ThrowsAsync(async () => await endPoint.CreateRxSocketClientAsync(Logger)); 28 | Assert.Equal((int)SocketError.ConnectionRefused, e.ErrorCode); 29 | } 30 | 31 | [Fact] 32 | public async Task T02_Timeout() 33 | { 34 | IPEndPoint endPoint = TestUtilities.GetEndPointOnRandomLoopbackPort(); 35 | CancellationTokenSource cts = new(TimeSpan.FromMilliseconds(1)); 36 | CancellationToken ct = cts.Token; 37 | //await Assert.ThrowsAsync(async () => 38 | await Assert.ThrowsAnyAsync(async () => 39 | await endPoint.CreateRxSocketClientAsync(Logger, ct)); 40 | } 41 | 42 | [Fact] 43 | public async Task T03_Cancellation() 44 | { 45 | IPEndPoint endPoint = TestUtilities.GetEndPointOnRandomLoopbackPort(); 46 | CancellationToken ct = new(true); 47 | await Assert.ThrowsAnyAsync(async () => 48 | await endPoint.CreateRxSocketClientAsync(Logger, ct)); 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /RxSockets.Tests/Extensions/ToStringArraysTest.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using System.Text; 3 | namespace RxSockets.Tests; 4 | 5 | public class ToStringArraysTest 6 | { 7 | private readonly MemoryStream ms = new(); 8 | 9 | private void AddMessage(string str) 10 | { 11 | long start = ms.Position; 12 | ms.Position += 4; 13 | Encoding.UTF8.GetBytes(str).ToList().ForEach(ms.WriteByte); 14 | ms.WriteByte(0); 15 | int len = Convert.ToInt32(ms.Position - start - 4); 16 | int prefix = IPAddress.NetworkToHostOrder(len); 17 | long lastPos = ms.Position; 18 | ms.Position = start; 19 | BitConverter.GetBytes(prefix).ToList().ForEach(ms.WriteByte); 20 | ms.Position = lastPos; 21 | } 22 | 23 | [Fact] 24 | public void T01_Test_String() 25 | { 26 | AddMessage("A\0BC\0"); 27 | string[][] messages = ms.ToArray().ToArraysFromBytesWithLengthPrefix().ToStringArrays().ToArray(); 28 | Assert.Single(messages); // 1 message 29 | string[] message1 = messages[0]; 30 | Assert.Equal(3, message1.Length); // containing 3 strings 31 | Assert.Equal("A", message1[0]); 32 | Assert.Equal("BC", message1[1]); 33 | Assert.Equal("", message1[2]); 34 | } 35 | 36 | [Fact] 37 | public void T02_Test_Message() 38 | { 39 | AddMessage("A\0BC\0"); 40 | AddMessage("D"); 41 | AddMessage(""); 42 | byte[] array = ms.ToArray(); 43 | 44 | string[][] messages = array.ToArraysFromBytesWithLengthPrefix().ToStringArrays().ToArray(); 45 | Assert.Equal(3, messages.Length); // 3 messages 46 | string[] message1 = messages[0]; // message 1 47 | Assert.Equal(3, message1.Length); // contains 3 strings 48 | Assert.Equal("A", message1[0]); 49 | Assert.Equal("BC", message1[1]); 50 | Assert.Equal("", message1[2]); 51 | 52 | string[] message2 = messages[1]; 53 | Assert.Single(message2); 54 | Assert.Equal("D", message2[0]); 55 | 56 | string[] message3 = messages[2]; 57 | Assert.Single(message3); 58 | Assert.Equal("", message3[0]); 59 | } 60 | 61 | } 62 | 63 | -------------------------------------------------------------------------------- /RxSockets.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.0.32112.339 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RxSockets", "RxSockets\RxSockets.csproj", "{FE7493C4-5CBB-440D-9BA2-A480E286BB3B}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{3BD54ADD-5084-490E-95CC-F0AED74C2936}" 9 | ProjectSection(SolutionItems) = preProject 10 | appveyor.yml = appveyor.yml 11 | ~\notes.txt = ~\notes.txt 12 | README.md = README.md 13 | EndProjectSection 14 | EndProject 15 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RxSockets.Tests", "RxSockets.Tests\RxSockets.Tests.csproj", "{B84F0916-D034-4CBD-8EA3-9B934F5D398D}" 16 | EndProject 17 | Global 18 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 19 | Debug|Any CPU = Debug|Any CPU 20 | Debug|x64 = Debug|x64 21 | Release|Any CPU = Release|Any CPU 22 | Release|x64 = Release|x64 23 | EndGlobalSection 24 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 25 | {FE7493C4-5CBB-440D-9BA2-A480E286BB3B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 26 | {FE7493C4-5CBB-440D-9BA2-A480E286BB3B}.Debug|Any CPU.Build.0 = Debug|Any CPU 27 | {FE7493C4-5CBB-440D-9BA2-A480E286BB3B}.Debug|x64.ActiveCfg = Debug|Any CPU 28 | {FE7493C4-5CBB-440D-9BA2-A480E286BB3B}.Debug|x64.Build.0 = Debug|Any CPU 29 | {FE7493C4-5CBB-440D-9BA2-A480E286BB3B}.Release|Any CPU.ActiveCfg = Release|Any CPU 30 | {FE7493C4-5CBB-440D-9BA2-A480E286BB3B}.Release|Any CPU.Build.0 = Release|Any CPU 31 | {FE7493C4-5CBB-440D-9BA2-A480E286BB3B}.Release|x64.ActiveCfg = Release|x64 32 | {FE7493C4-5CBB-440D-9BA2-A480E286BB3B}.Release|x64.Build.0 = Release|x64 33 | {B84F0916-D034-4CBD-8EA3-9B934F5D398D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 34 | {B84F0916-D034-4CBD-8EA3-9B934F5D398D}.Debug|Any CPU.Build.0 = Debug|Any CPU 35 | {B84F0916-D034-4CBD-8EA3-9B934F5D398D}.Debug|x64.ActiveCfg = Debug|Any CPU 36 | {B84F0916-D034-4CBD-8EA3-9B934F5D398D}.Debug|x64.Build.0 = Debug|Any CPU 37 | {B84F0916-D034-4CBD-8EA3-9B934F5D398D}.Release|Any CPU.ActiveCfg = Release|Any CPU 38 | {B84F0916-D034-4CBD-8EA3-9B934F5D398D}.Release|Any CPU.Build.0 = Release|Any CPU 39 | {B84F0916-D034-4CBD-8EA3-9B934F5D398D}.Release|x64.ActiveCfg = Release|Any CPU 40 | {B84F0916-D034-4CBD-8EA3-9B934F5D398D}.Release|x64.Build.0 = Release|Any CPU 41 | EndGlobalSection 42 | GlobalSection(SolutionProperties) = preSolution 43 | HideSolutionNode = FALSE 44 | EndGlobalSection 45 | GlobalSection(ExtensibilityGlobals) = postSolution 46 | SolutionGuid = {FA85F050-4080-4F5C-8B35-19693B672AEC} 47 | EndGlobalSection 48 | EndGlobal 49 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /RxSockets/Extensions/RxSocketsExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging.Abstractions; 2 | namespace RxSockets; 3 | 4 | public static partial class Extension 5 | { 6 | /// 7 | /// Create a connected RxSocketClient. 8 | /// 9 | public static async Task CreateRxSocketClientAsync(this EndPoint endPoint, CancellationToken ct = default) => 10 | await CreateRxSocketClientAsync(endPoint, NullLogger.Instance, ct).ConfigureAwait(false); 11 | 12 | /// 13 | /// Create a connected RxSocketClient. 14 | /// 15 | public static async Task CreateRxSocketClientAsync(this EndPoint endPoint, ILoggerFactory factoryLogger, CancellationToken ct = default) => 16 | await CreateRxSocketClientAsync(endPoint, factoryLogger.CreateLogger(), ct).ConfigureAwait(false); 17 | 18 | /// 19 | /// Create a connected RxSocketClient. 20 | /// 21 | public static async Task CreateRxSocketClientAsync(this EndPoint endPoint, ILogger logger, CancellationToken ct = default) 22 | { 23 | ArgumentNullException.ThrowIfNull(endPoint); 24 | Socket socket = await ConnectAsync(endPoint, logger, ct).ConfigureAwait(false); 25 | return new RxSocketClient(socket, logger, "Client"); 26 | } 27 | 28 | private static async Task ConnectAsync(EndPoint endPoint, ILogger logger, CancellationToken ct) 29 | { 30 | Socket socket = Utilities.CreateSocket(); 31 | try 32 | { 33 | await socket.ConnectAsync(endPoint, ct).ConfigureAwait(false); 34 | logger.LogInformation("Client on {LocalEndPoint} connected to {EndPoint}.", socket.LocalEndPoint, endPoint); 35 | return socket; 36 | } 37 | catch (Exception e) 38 | { 39 | if (e is SocketException se) 40 | { 41 | string errorName = $"SocketException: {Enum.GetName(typeof(SocketError), se.ErrorCode)}"; 42 | logger.LogWarning("Socket could not connect to {EndPoint}. {Message} {ErrorName}.", endPoint, e.Message, errorName); 43 | } 44 | else 45 | logger.LogWarning("Socket could not connect to {EndPoint}. {Message}", endPoint, e.Message); 46 | throw; 47 | } 48 | } 49 | 50 | public static IRxSocketServer CreateRxSocketServer(this EndPoint endPoint, int backLog = 10) => 51 | RxSocketServer.Create(endPoint, NullLoggerFactory.Instance, backLog); 52 | 53 | public static IRxSocketServer CreateRxSocketServer(this EndPoint endPoint, ILoggerFactory loggerFactory, int backLog = 10) => 54 | RxSocketServer.Create(endPoint, loggerFactory, backLog); 55 | } 56 | -------------------------------------------------------------------------------- /RxSockets/Utilities/SocketDisposer.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics.CodeAnalysis; 2 | 3 | namespace RxSockets; 4 | 5 | internal sealed class SocketDisposer : IAsyncDisposable 6 | { 7 | private readonly ILogger Logger; 8 | private readonly Socket Socket; 9 | private readonly IAsyncDisposable Disposable; 10 | private readonly string Name; 11 | private readonly TaskCompletionSource Tcs = new(TaskCreationOptions.RunContinuationsAsynchronously); 12 | private readonly CancellationTokenSource ReceiveCts; 13 | private int Disposals; // state 14 | internal bool DisposeRequested => Disposals > 0; 15 | 16 | internal SocketDisposer(Socket socket, string name, ILogger logger, CancellationTokenSource receiveCts) : 17 | this(socket, AsyncEmptyDisposable.Instance, name, logger, receiveCts) { } 18 | internal SocketDisposer(Socket socket, IAsyncDisposable disposable, string name, ILogger logger, CancellationTokenSource receiveCts) 19 | { 20 | Socket = socket; 21 | ReceiveCts = receiveCts; 22 | Logger = logger; 23 | Name = name; 24 | Disposable = disposable; 25 | } 26 | 27 | [SuppressMessage("Usage", "CA1031:Catch more specific exception type.")] 28 | public async ValueTask DisposeAsync() 29 | { 30 | if (Interlocked.Increment(ref Disposals) > 1) 31 | { 32 | await Tcs.Task.ConfigureAwait(false); 33 | return; 34 | } 35 | 36 | try 37 | { 38 | await ReceiveCts.CancelAsync().ConfigureAwait(false); 39 | 40 | EndPoint? localEndPoint = Socket.LocalEndPoint; 41 | EndPoint? remoteEndPoint = Socket.RemoteEndPoint; 42 | 43 | if (Socket.Connected) 44 | { 45 | // disables Send method and queues up a zero-byte send packet in the send buffer 46 | Socket.Shutdown(SocketShutdown.Send); 47 | await Socket.DisconnectAsync(false).ConfigureAwait(false); 48 | Logger.LogDebug("{Name} on {LocalEndPoint} disconnected from {RemoteEndPoint} and disposed.", Name, localEndPoint, remoteEndPoint); 49 | } 50 | else 51 | { 52 | Logger.LogDebug("{Name} on {LocalEndPoint} disposed.", Name, localEndPoint); 53 | } 54 | 55 | // SocketAcceptor or AsyncEmptyDisposable 56 | await Disposable.DisposeAsync().ConfigureAwait(false); 57 | } 58 | catch (Exception e) 59 | { 60 | Logger.LogWarning(e, "DisposeAsync."); 61 | } 62 | 63 | try 64 | { 65 | Socket.Dispose(); 66 | Tcs.SetResult(true); 67 | } 68 | catch (Exception e) 69 | { 70 | Logger.LogWarning(e, "DisposeAsync."); 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /RxSockets.Tests/Examples/SimpleExample.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | namespace RxSockets.Tests; 3 | 4 | public class SimpleExample 5 | { 6 | [Fact] 7 | public async Task AsyncEnumerable_Example() 8 | { 9 | // Create a server on the local machine using a random available port. 10 | IRxSocketServer server = RxSocketServer.Create(); 11 | 12 | Task task = Task.Run(async () => 13 | { 14 | await foreach (IRxSocketClient acceptClient in server.AcceptAllAsync) 15 | { 16 | await foreach (string msg in acceptClient.ReceiveAllAsync.ToStrings()) 17 | { 18 | // Echo each message received back to the client. 19 | acceptClient.Send(msg.ToByteArray()); 20 | } 21 | } 22 | }); 23 | 24 | // Create a client by connecting to the server. 25 | IRxSocketClient client = await server.LocalEndPoint.CreateRxSocketClientAsync(); 26 | 27 | // Send the message "Hello" to the server, which the server will then echo back to the client. 28 | client.Send("Hello!".ToByteArray()); 29 | 30 | // Receive the message from the server. 31 | string message = await client.ReceiveAllAsync.ToStrings().FirstAsync(); 32 | Assert.Equal("Hello!", message); 33 | 34 | await client.DisposeAsync(); 35 | await server.DisposeAsync(); 36 | } 37 | 38 | [Fact] 39 | public async Task Observable_Example() 40 | { 41 | // Create a server on an available port on the local machine. 42 | IRxSocketServer server = RxSocketServer.Create(); 43 | 44 | // Start accepting connections from clients. 45 | server 46 | .AcceptObservable 47 | .Subscribe(onNext: acceptClient => 48 | { 49 | // After the server accepts a client connection, 50 | // start receiving messages from the client and ... 51 | acceptClient 52 | .ReceiveObservable 53 | .ToStrings() 54 | .Subscribe(onNext: message => 55 | { 56 | // Echo each message received back to the client. 57 | acceptClient.Send(message.ToByteArray()); 58 | }); 59 | }); 60 | 61 | // Create a client connected to the EndPoint of the server. 62 | IRxSocketClient client = await server.LocalEndPoint.CreateRxSocketClientAsync(); 63 | 64 | // Send the message "Hello" to the server, which the server will then echo back to the client. 65 | client.Send("Hello!".ToByteArray()); 66 | 67 | // Receive the message from the server. 68 | string message = await client.ReceiveObservable.ToStrings().FirstAsync(); 69 | 70 | Assert.Equal("Hello!", message); 71 | 72 | await client.DisposeAsync(); 73 | await server.DisposeAsync(); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /RxSockets/RxSocketServer.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging.Abstractions; 2 | namespace RxSockets; 3 | 4 | public interface IRxSocketServer : IAsyncDisposable 5 | { 6 | EndPoint LocalEndPoint { get; } 7 | IObservable AcceptObservable { get; } 8 | IAsyncEnumerable AcceptAllAsync { get; } 9 | } 10 | 11 | public sealed class RxSocketServer : IRxSocketServer 12 | { 13 | private readonly CancellationTokenSource Cts = new(); 14 | private readonly SocketAcceptor Acceptor; 15 | private readonly SocketDisposer Disposer; 16 | public EndPoint LocalEndPoint { get; } 17 | public IObservable AcceptObservable { get; } 18 | public IAsyncEnumerable AcceptAllAsync { get; } 19 | 20 | private RxSocketServer(Socket socket, ILogger logger) 21 | { 22 | LocalEndPoint = socket.LocalEndPoint ?? throw new InvalidOperationException(); 23 | Acceptor = new SocketAcceptor(socket, logger, Cts.Token); 24 | Disposer = new SocketDisposer(socket, Acceptor, "Server", logger, Cts); 25 | AcceptObservable = Acceptor.CreateAcceptObservable(); 26 | AcceptAllAsync = Acceptor.CreateAcceptAllAsync(Cts.Token); 27 | logger.LogInformation("Server on {LocalEndPoint} created.", LocalEndPoint); 28 | } 29 | 30 | public async ValueTask DisposeAsync() 31 | { 32 | await Acceptor.DisposeAsync().ConfigureAwait(false); 33 | await Disposer.DisposeAsync().ConfigureAwait(false); 34 | Cts.Dispose(); 35 | } 36 | 37 | /// 38 | /// Create a RxSocketServer. 39 | /// 40 | public static IRxSocketServer Create(Socket socket, ILoggerFactory loggerFactory) 41 | { 42 | ArgumentNullException.ThrowIfNull(socket); 43 | return new RxSocketServer(socket, loggerFactory.CreateLogger()); 44 | } 45 | 46 | /// 47 | /// Create an RxSocketServer on EndPoint. 48 | /// 49 | public static IRxSocketServer Create(EndPoint endPoint, ILoggerFactory loggerFactory, int backLog = 10) 50 | { 51 | ArgumentNullException.ThrowIfNull(endPoint); 52 | // Backlog specifies the number of pending connections allowed before a busy error is returned. 53 | if (backLog < 0) 54 | throw new ArgumentException($"Invalid backLog: {backLog}."); 55 | Socket socket = Utilities.CreateSocket(); 56 | socket.Bind(endPoint); 57 | socket.Listen(backLog); 58 | return Create(socket, loggerFactory); 59 | } 60 | 61 | /// 62 | /// Create a RxSocketServer on an available port on the localhost. 63 | /// 64 | public static IRxSocketServer Create(int backLog = 10) => 65 | Create(Utilities.CreateIPEndPointOnPort(0), NullLoggerFactory.Instance, backLog); 66 | 67 | /// 68 | /// Create a RxSocketServer on an available port on the localhost. 69 | /// 70 | public static IRxSocketServer Create(ILoggerFactory loggerFactory, int backLog = 10) => 71 | Create(Utilities.CreateIPEndPointOnPort(0), loggerFactory, backLog); 72 | } 73 | -------------------------------------------------------------------------------- /RxSockets.Tests/Utility/Socket_Disposer_Tests.cs: -------------------------------------------------------------------------------- 1 | using System.Threading; 2 | using System.Threading.Tasks; 3 | namespace RxSockets.Tests; 4 | 5 | public class Socket_Disposer_Tests(ITestOutputHelper output) : TestBase(output) 6 | { 7 | private readonly CancellationTokenSource Cts = new(); 8 | 9 | [Fact] 10 | public async Task T01_Dispose_Not_Connected_Socket() 11 | { 12 | Socket socket = Utilities.CreateSocket(); 13 | SocketDisposer disposer = new(socket, "?", Logger, Cts); 14 | await disposer.DisposeAsync(); 15 | Assert.True(disposer.DisposeRequested); 16 | Assert.False(socket.Connected); 17 | } 18 | 19 | [Fact] 20 | public async Task T02_Dispose_Connected_Socket() 21 | { 22 | EndPoint endPoint = TestUtilities.GetEndPointOnRandomLoopbackPort(); 23 | Socket serverSocket = Utilities.CreateSocket(); 24 | SocketDisposer serverDisposer = new(serverSocket, "?", Logger, Cts); 25 | serverSocket.Bind(endPoint); 26 | serverSocket.Listen(10); 27 | 28 | Socket clientSocket = Utilities.CreateSocket(); 29 | SocketDisposer clientDisposer = new(clientSocket, "?", Logger, Cts); 30 | await clientSocket.ConnectAsync(endPoint); 31 | Assert.False(clientDisposer.DisposeRequested); 32 | Assert.True(clientSocket.Connected); 33 | 34 | await clientDisposer.DisposeAsync(); 35 | 36 | Assert.True(clientDisposer.DisposeRequested); 37 | Assert.False(clientSocket.Connected); 38 | 39 | Assert.False(serverDisposer.DisposeRequested); 40 | Assert.False(serverSocket.Connected); 41 | 42 | await serverDisposer.DisposeAsync(); 43 | 44 | Assert.True(serverDisposer.DisposeRequested); 45 | Assert.False(serverSocket.Connected); 46 | } 47 | 48 | [Fact] 49 | public async Task T04_Dispose_Multi() 50 | { 51 | EndPoint endPoint = TestUtilities.GetEndPointOnRandomLoopbackPort(); 52 | Socket serverSocket = Utilities.CreateSocket(); 53 | serverSocket.Bind(endPoint); 54 | serverSocket.Listen(10); 55 | 56 | Socket socket = Utilities.CreateSocket(); 57 | SocketDisposer disposer = new(socket, "?", Logger, Cts); 58 | await socket.ConnectAsync(endPoint); 59 | Assert.True(socket.Connected); 60 | Assert.False(disposer.DisposeRequested); 61 | 62 | System.Collections.Generic.List disposeTasks = Enumerable.Range(1, 8).Select((_) => disposer.DisposeAsync().AsTask()).ToList(); 63 | await Task.WhenAll(disposeTasks); 64 | Assert.True(disposer.DisposeRequested); 65 | } 66 | 67 | [Fact] 68 | public async Task T05_Dispose_Disposed_Socket() 69 | { 70 | EndPoint endPoint = TestUtilities.GetEndPointOnRandomLoopbackPort(); 71 | Socket serverSocket = Utilities.CreateSocket(); 72 | serverSocket.Bind(endPoint); 73 | serverSocket.Listen(10); 74 | 75 | Socket clientSocket = Utilities.CreateSocket(); 76 | SocketDisposer disposer = new(clientSocket, "?", Logger, Cts); 77 | Assert.False(disposer.DisposeRequested); 78 | 79 | await clientSocket.ConnectAsync(endPoint); 80 | Assert.True(clientSocket.Connected); 81 | 82 | clientSocket.Dispose(); 83 | await disposer.DisposeAsync(); // dispose disposed 84 | Assert.True(disposer.DisposeRequested); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /RxSockets/Utilities/SocketReceiver.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | using System.Diagnostics.CodeAnalysis; 3 | using System.Reactive.Linq; 4 | using System.Runtime.CompilerServices; 5 | namespace RxSockets; 6 | 7 | internal sealed class SocketReceiver 8 | { 9 | private readonly ILogger Logger; 10 | private readonly Socket Socket; 11 | private readonly CancellationToken ReceiveCt; 12 | private readonly string Name; 13 | private readonly byte[] Buffer = new byte[0x10000]; 14 | private int Position; 15 | private int BytesReceived; 16 | 17 | internal SocketReceiver(Socket socket, string name, ILogger logger, CancellationToken receiveCt) 18 | { 19 | Logger = logger; 20 | Socket = socket; 21 | ReceiveCt = receiveCt; 22 | Name = name; 23 | } 24 | 25 | [SuppressMessage("Usage", "CA1031:Catch more specific exception type.")] 26 | internal IObservable CreateReceiveObservable() 27 | { 28 | return Observable.Create(async (observer, ct) => 29 | { 30 | Logger.LogDebug("{Name}: SocketReceiverObservable subscribing.", Name); 31 | Debug.Assert(Thread.CurrentThread.IsBackground, "Not a background thread."); 32 | 33 | try 34 | { 35 | while (!ct.IsCancellationRequested) 36 | { 37 | if (Position == BytesReceived) 38 | { 39 | BytesReceived = await Socket.ReceiveAsync(Buffer, ct).ConfigureAwait(false); 40 | Position = 0; 41 | 42 | if (BytesReceived == 0) 43 | { 44 | observer.OnCompleted(); 45 | return; 46 | } 47 | 48 | Logger.LogReceive(Name, Socket.LocalEndPoint, BytesReceived, Socket.RemoteEndPoint); 49 | } 50 | observer.OnNext(Buffer[Position++]); 51 | } 52 | } 53 | catch (Exception ex) 54 | { 55 | if (ReceiveCt.IsCancellationRequested) 56 | { 57 | observer.OnCompleted(); 58 | return; 59 | } 60 | if (ct.IsCancellationRequested) 61 | return; 62 | Logger.LogDebug(ex, "{Name}: SocketReceiverObservable Exception: {Message}", Name, ex.Message); 63 | observer.OnError(ex); 64 | } 65 | }); 66 | } 67 | 68 | internal async IAsyncEnumerable ReceiveAllAsync([EnumeratorCancellation] CancellationToken ct = default) 69 | { 70 | while (!ct.IsCancellationRequested) 71 | { 72 | if (Position == BytesReceived) 73 | { 74 | try 75 | { 76 | BytesReceived = await Socket.ReceiveAsync(Buffer, ct).ConfigureAwait(false); 77 | Position = 0; 78 | } 79 | catch (Exception) 80 | { 81 | if (ct.IsCancellationRequested || ReceiveCt.IsCancellationRequested) 82 | yield break; 83 | throw; 84 | } 85 | 86 | if (BytesReceived == 0) 87 | yield break; 88 | 89 | Logger.LogReceive(Name, Socket.LocalEndPoint, BytesReceived, Socket.RemoteEndPoint); 90 | } 91 | yield return Buffer[Position++]; 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /RxSockets/Utilities/SocketAcceptor.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | using System.Diagnostics.CodeAnalysis; 3 | using System.Reactive.Linq; 4 | using System.Runtime.CompilerServices; 5 | namespace RxSockets; 6 | 7 | internal sealed class SocketAcceptor : IAsyncDisposable 8 | { 9 | private readonly ILogger Logger; 10 | private readonly Socket Socket; 11 | private readonly CancellationToken serverCt; 12 | private readonly List Connections = []; // state 13 | 14 | internal SocketAcceptor(Socket socket, ILogger logger, CancellationToken ct) 15 | { 16 | Socket = socket; 17 | Logger = logger; 18 | serverCt = ct; 19 | } 20 | 21 | [SuppressMessage("Usage", "CA1031:Catch more specific exception type.")] 22 | internal IObservable CreateAcceptObservable() 23 | { 24 | return Observable.Create(async (observer, ct) => 25 | { 26 | Debug.Assert(Thread.CurrentThread.IsBackground, "Not a background thread."); 27 | 28 | while (!ct.IsCancellationRequested) 29 | { 30 | try 31 | { 32 | Socket acceptSocket = await Socket.AcceptAsync(ct).ConfigureAwait(false); 33 | observer.OnNext(CreateClient(acceptSocket)); 34 | } 35 | catch (Exception e) 36 | { 37 | if (serverCt.IsCancellationRequested) 38 | { 39 | observer.OnCompleted(); 40 | return; 41 | } 42 | if (ct.IsCancellationRequested) 43 | return; 44 | Logger.LogError("SocketAcceptor: {Message}", e.Message); 45 | observer.OnError(e); 46 | return; 47 | } 48 | } 49 | }); 50 | } 51 | 52 | // CancellationToken is linked to the one in the producer using CreateLinkedTokenSource so that 53 | // consumer can cancel using cooperative cancellation implemented in the producer so not only 54 | // we can cancel consuming, but also, producing.\ 55 | // ConfiguredCancelableAsyncEnumerable ae = AcceptAllAsync.WithCancelation(ct); 56 | internal async IAsyncEnumerable CreateAcceptAllAsync([EnumeratorCancellation] CancellationToken ct) 57 | { 58 | Socket acceptSocket; 59 | while (!ct.IsCancellationRequested) 60 | { 61 | try 62 | { 63 | acceptSocket = await Socket.AcceptAsync(ct).ConfigureAwait(false); 64 | } 65 | catch (Exception e) 66 | { 67 | if (ct.IsCancellationRequested) 68 | yield break; 69 | Logger.LogError("SocketAcceptor: {Message}", e.Message); 70 | throw; 71 | } 72 | yield return CreateClient(acceptSocket); 73 | } 74 | } 75 | 76 | private RxSocketClient CreateClient(Socket acceptSocket) 77 | { 78 | Logger.LogDebug("AcceptClient on {LocalEndPoint} connected to {RemoteEndPoint}.", Socket.LocalEndPoint, acceptSocket.RemoteEndPoint); 79 | RxSocketClient client = new(acceptSocket, Logger, "AcceptClient"); 80 | Connections.Add(client); 81 | return client; 82 | } 83 | 84 | public async ValueTask DisposeAsync() 85 | { 86 | IEnumerable tasks = Connections.Select(client => client.DisposeAsync().AsTask()); 87 | await Task.WhenAll(tasks).ConfigureAwait(false); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /RxSockets/Extensions/StringExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using System.Reactive.Linq; 3 | using System.Text; 4 | namespace RxSockets; 5 | 6 | public static partial class Extension 7 | { 8 | /// 9 | /// Convert a string to a byte array. 10 | /// 11 | public static byte[] ToByteArray(this string source) => 12 | Encoding.UTF8.GetBytes(source + '\0'); 13 | 14 | /// 15 | /// Convert a sequence of strings to a byte array. 16 | /// 17 | public static byte[] ToByteArray(this IEnumerable source) => 18 | [.. source.SelectMany(s => s.ToByteArray())]; 19 | 20 | /////////////////////////////////////////////////////////////// 21 | 22 | /// 23 | /// Convert a sequence of bytes into a sequence of strings. 24 | /// 25 | public static IEnumerable ToStrings(this IEnumerable source) 26 | { 27 | ArgumentNullException.ThrowIfNull(source); 28 | 29 | using MemoryStream ms = new(); 30 | foreach (byte b in source) 31 | { 32 | if (b != 0) 33 | { 34 | ms.WriteByte(b); 35 | continue; 36 | } 37 | string s = Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Position); 38 | ms.SetLength(0); 39 | yield return s; 40 | } 41 | if (ms.Position != 0) 42 | throw new InvalidDataException("ToStrings: no termination(1)."); 43 | } 44 | 45 | /// 46 | /// Transform a sequence of bytes into a sequence of strings. 47 | /// 48 | public static async IAsyncEnumerable ToStrings(this IAsyncEnumerable source) 49 | { 50 | using MemoryStream ms = new(); 51 | await foreach (byte b in source.ConfigureAwait(false)) 52 | { 53 | if (b != 0) 54 | { 55 | ms.WriteByte(b); 56 | continue; 57 | } 58 | string s = Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Position); 59 | ms.SetLength(0); 60 | yield return s; 61 | } 62 | if (ms.Position != 0) 63 | throw new InvalidDataException("ToStrings: invalid termination."); 64 | } 65 | 66 | /// 67 | /// Convert a sequence of bytes into a sequence of strings. 68 | /// 69 | public static IObservable ToStrings(this IObservable source) 70 | { 71 | MemoryStream ms = new(); 72 | 73 | return Observable.Create(observer => 74 | { 75 | return source.Subscribe( 76 | onNext: b => 77 | { 78 | if (b != 0) 79 | { 80 | ms.WriteByte(b); 81 | return; 82 | } 83 | string s = Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Position); 84 | ms.SetLength(0); 85 | observer.OnNext(s); 86 | }, 87 | onError: (e) => 88 | { 89 | observer.OnError(e); 90 | ms.Dispose(); 91 | }, 92 | onCompleted: () => 93 | { 94 | if (ms.Position == 0) 95 | observer.OnCompleted(); 96 | else 97 | observer.OnError(new InvalidDataException("ToStrings: invalid termination.")); 98 | ms.Dispose(); 99 | }); 100 | }); 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /RxSockets.Tests/Tests/PerformanceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Diagnostics; 2 | using System.Reactive.Threading.Tasks; 3 | using System.Threading.Tasks; 4 | namespace RxSockets.Tests; 5 | 6 | public class PerformanceTest1(ITestOutputHelper output) : TestBase(output) 7 | { 8 | const int numberOfMessages = 100_000; 9 | 10 | [Fact] 11 | public async Task T01_ReceiveStrings() 12 | { 13 | IRxSocketServer server = RxSocketServer.Create(); 14 | EndPoint endPoint = server.LocalEndPoint; 15 | 16 | ValueTask acceptFirstClientTask = server.AcceptAllAsync.FirstAsync(); 17 | IRxSocketClient client = await endPoint.CreateRxSocketClientAsync(); 18 | IRxSocketClient acceptClient = await acceptFirstClientTask; 19 | Task countTask = acceptClient.ReceiveObservable.ToStrings().Count().ToTask(); 20 | //ValueTask countTask = acceptClient.ReceiveAllAsync.ToStrings().CountAsync(); 21 | 22 | byte[] message = "Welcome!".ToByteArray(); 23 | client.Send(message); 24 | 25 | Stopwatch watch = new(); 26 | watch.Start(); 27 | 28 | // send messages from server to client 29 | for (int i = 0; i < numberOfMessages - 1; i++) 30 | client.Send(message); 31 | 32 | // end countTask 33 | await client.DisposeAsync(); 34 | int count = await countTask; 35 | watch.Stop(); 36 | 37 | Assert.Equal(numberOfMessages, count); 38 | 39 | long frequency = Stopwatch.Frequency * numberOfMessages / watch.ElapsedTicks; 40 | Write($"{frequency:N0} messages / second"); 41 | 42 | await server.DisposeAsync(); 43 | } 44 | } 45 | 46 | public class PerformanceTest2(ITestOutputHelper output) : TestBase(output) 47 | { 48 | const int numberOfMessages = 100_000; 49 | 50 | [Fact] 51 | public async Task T02_ReceiveStringsFromPrefixedBytes() 52 | { 53 | IRxSocketServer server = RxSocketServer.Create(); 54 | EndPoint endPoint = server.LocalEndPoint; 55 | ValueTask acceptFirstClientTask = server.AcceptAllAsync.FirstAsync(); 56 | 57 | IRxSocketClient client = await endPoint.CreateRxSocketClientAsync(); 58 | Assert.True(client.Connected); 59 | 60 | Task countTask = client 61 | .ReceiveObservable 62 | .ToArraysFromBytesWithLengthPrefix() 63 | .ToStringArrays() 64 | .Count() 65 | .ToTask(); 66 | /* 67 | ValueTask countTask = client 68 | .ReceiveAllAsync 69 | .ToArraysFromBytesWithLengthPrefix() 70 | .ToStringArrays() 71 | .CountAsync(); 72 | */ 73 | 74 | IRxSocketClient acceptClient = await acceptFirstClientTask; 75 | Assert.True(acceptClient.Connected); 76 | 77 | byte[] message = new[] { "Welcome!" }.ToByteArray().ToByteArrayWithLengthPrefix(); 78 | 79 | acceptClient.Send("1".ToByteArray().ToByteArrayWithLengthPrefix()); 80 | 81 | Stopwatch watch = new(); 82 | watch.Start(); 83 | 84 | for (int i = 0; i < numberOfMessages - 1; i++) 85 | acceptClient.Send(message); 86 | 87 | // end count task 88 | await acceptClient.DisposeAsync(); 89 | int count = await countTask; 90 | 91 | watch.Stop(); 92 | Assert.Equal(numberOfMessages, count); 93 | 94 | long frequency = Stopwatch.Frequency * numberOfMessages / watch.ElapsedTicks; 95 | Write($"{frequency:N0} messages / second"); 96 | 97 | await client.DisposeAsync(); 98 | await server.DisposeAsync(); 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # RxSockets   [![Build status](https://ci.appveyor.com/api/projects/status/rfxxbpx2agq8r93n?svg=true)](https://ci.appveyor.com/project/dshe/RxSockets) [![NuGet](https://img.shields.io/nuget/vpre/RxSockets.svg)](https://www.nuget.org/packages/RxSockets/) [![NuGet](https://img.shields.io/nuget/dt/RxSockets?color=orange)](https://www.nuget.org/packages/RxSockets/) [![License](https://img.shields.io/badge/license-Apache%202.0-7755BB.svg)](https://opensource.org/licenses/Apache-2.0) 2 | ***Minimal Reactive / Async Streams Socket Implementation*** 3 | - **.NET 8.0** library 4 | - connect: *asynchronous* 5 | - send: *synchronous* 6 | - receive: *observable* or *async enumerable* 7 | - accept: *observable* or *async enumerable* 8 | - simple and intuitive API 9 | - major dependencies: System.Reactive 10 | 11 | ### installation 12 | ```csharp 13 | PM> Install-Package RxSockets 14 | ``` 15 | ### example 16 | ```csharp 17 | using System.Reactive.Linq; 18 | using System.Linq; 19 | using Xunit; 20 | using RxSockets; 21 | ``` 22 | #### Server 23 | ```csharp 24 | interface IRxSocketServer : IAsyncDisposable 25 | { 26 | EndPoint LocalEndPoint { get; } 27 | IObservable AcceptObservable { get; } 28 | IAsyncEnumerable AcceptAllAsync { get; } 29 | } 30 | ``` 31 | ```csharp 32 | // Create a server using an available port on the local machine. 33 | IRxSocketServer server = RxSocketServer.Create(); 34 | 35 | // Prepare to start accepting connections from clients. 36 | server 37 | .AcceptObservable 38 | .Subscribe(onNext: acceptClient => 39 | { 40 | // After the server accepts a client connection, 41 | // start receiving messages from the client and ... 42 | acceptClient 43 | .ReceiveObservable 44 | .ToStrings() 45 | .Subscribe(onNext: message => 46 | { 47 | // Echo each message received back to the client. 48 | acceptClient.Send(message.ToByteArray()); 49 | }); 50 | }); 51 | ``` 52 | #### Client 53 | ```csharp 54 | interface IRxSocketClient : IAsyncDisposable 55 | { 56 | EndPoint RemoteEndPoint { get; } 57 | bool Connected { get; } 58 | int Send(ReadOnlySpan buffer); 59 | IObservable ReceiveObservable { get; } 60 | IAsyncEnumerable ReceiveAllAsync { get; } 61 | } 62 | ``` 63 | ```csharp 64 | // Create a client connected to EndPoint of the server. 65 | IRxSocketClient client = await server.LocalEndPoint.CreateRxSocketClientAsync(); 66 | 67 | // Send the message "Hello!" to the server, 68 | // which the server will then echo back to the client. 69 | client.Send("Hello!".ToByteArray()); 70 | 71 | // Receive the message from the server. 72 | string message = await client.ReceiveAllAsync.ToStrings().FirstAsync(); 73 | Assert.Equal("Hello!", message); 74 | 75 | await client.DisposeAsync(); 76 | await server.DisposeAsync(); 77 | ``` 78 | ### notes 79 | To communicate using strings (see example above), the following extension methods are provided: 80 | ```csharp 81 | byte[] ToByteArray(this string source); 82 | byte[] ToByteArray(this IEnumerable source) 83 | 84 | IEnumerable ToStrings(this IEnumerable source) 85 | IObservable ToStrings(this IObservable source) 86 | IAsyncEnumerable ToStrings(this IAsyncEnumerable source) 87 | ``` 88 | To communicate using byte arrays with a 4 byte BigEndian integer length prefix, the following extension methods are provided: 89 | ```csharp 90 | byte[] ToByteArrayWithLengthPrefix(this byte[] source) 91 | 92 | IEnumerable ToArraysFromBytesWithLengthPrefix(this IEnumerable source) 93 | IObservable ToArraysFromBytesWithLengthPrefix(this IObservable source) 94 | IAsyncEnumerable ToArraysFromBytesWithLengthPrefix(this IAsyncEnumerable source) 95 | ``` 96 | To support multiple simultaneous observers, use: 97 | ```csharp 98 | Observable.Publish().[RefCount() | AutoConnect()] 99 | ``` 100 | 101 | -------------------------------------------------------------------------------- /RxSockets.Tests/Tests/ClientTests.cs: -------------------------------------------------------------------------------- 1 | using System.Threading; 2 | using System.Threading.Tasks; 3 | namespace RxSockets.Tests; 4 | 5 | public class ClientTests(ITestOutputHelper output) : TestBase(output) 6 | { 7 | [Fact] 8 | public async Task T00_All_Ok() 9 | { 10 | IRxSocketServer server = RxSocketServer.Create(LogFactory); 11 | IRxSocketClient client = await server.LocalEndPoint.CreateRxSocketClientAsync(Logger); 12 | await server.AcceptAllAsync.FirstAsync(); 13 | await client.DisposeAsync(); 14 | await server.DisposeAsync(); 15 | } 16 | 17 | [Fact] 18 | public async Task T00_Cancellation_During_Connect() 19 | { 20 | IPEndPoint endPoint = TestUtilities.GetEndPointOnRandomLoopbackPort(); 21 | await Assert.ThrowsAnyAsync(async () => 22 | await endPoint.CreateRxSocketClientAsync(LogFactory, ct: new CancellationToken(true))); 23 | } 24 | 25 | [Fact] 26 | public async Task T00_Timeout_During_Connect() 27 | { 28 | IPEndPoint endPoint = TestUtilities.GetEndPointOnRandomLoopbackPort(); 29 | await Assert.ThrowsAsync(async () => 30 | await endPoint.CreateRxSocketClientAsync(LogFactory)); 31 | } 32 | 33 | [Fact] 34 | public async Task T01_Dispose_Before_Receive() 35 | { 36 | IRxSocketServer server = RxSocketServer.Create(LogFactory); 37 | IRxSocketClient client = await server.LocalEndPoint.CreateRxSocketClientAsync(LogFactory); 38 | await client.DisposeAsync(); 39 | await Assert.ThrowsAsync(async () => await client.ReceiveAllAsync.FirstAsync()); 40 | await server.DisposeAsync(); 41 | } 42 | 43 | [Fact] 44 | public async Task T02_Dispose_During_Receive() 45 | { 46 | IRxSocketServer server = RxSocketServer.Create(LogFactory); 47 | 48 | IRxSocketClient client = await server.LocalEndPoint.CreateRxSocketClientAsync(LogFactory); 49 | ValueTask receiveTask = client.ReceiveAllAsync.LastOrDefaultAsync(); 50 | await client.DisposeAsync(); 51 | 52 | await receiveTask; // does not throw 53 | 54 | await server.DisposeAsync(); 55 | } 56 | 57 | [Fact] 58 | public async Task T03_External_Dispose_Before_Receive() 59 | { 60 | IRxSocketServer server = RxSocketServer.Create(LogFactory); 61 | IRxSocketClient client = await server.LocalEndPoint.CreateRxSocketClientAsync(LogFactory); 62 | IRxSocketClient accept = await server.AcceptAllAsync.FirstAsync(); 63 | await accept.DisposeAsync(); 64 | await client.ReceiveAllAsync.LastOrDefaultAsync(); 65 | await client.DisposeAsync(); 66 | await server.DisposeAsync(); 67 | } 68 | 69 | [Fact] 70 | public async Task T04_External_Dispose_During_Receive() 71 | { 72 | IRxSocketServer server = RxSocketServer.Create(LogFactory); 73 | IRxSocketClient client = await server.LocalEndPoint.CreateRxSocketClientAsync(LogFactory); 74 | IRxSocketClient accept = await server.AcceptAllAsync.FirstAsync(); 75 | ValueTask receiveTask = client.ReceiveAllAsync.FirstAsync(); 76 | await accept.DisposeAsync(); 77 | await Assert.ThrowsAsync(async () => await receiveTask); 78 | await client.DisposeAsync(); 79 | await server.DisposeAsync(); 80 | } 81 | 82 | [Fact] 83 | public async Task T05_Dispose_Before_Send() 84 | { 85 | IRxSocketServer server = RxSocketServer.Create(LogFactory); 86 | IRxSocketClient client = await server.LocalEndPoint.CreateRxSocketClientAsync(LogFactory); 87 | await client.DisposeAsync(); 88 | Assert.ThrowsAny(() => client.Send([0])); 89 | await server.DisposeAsync(); 90 | } 91 | 92 | [Fact] 93 | public async Task T06_Dispose_During_Send() 94 | { 95 | IRxSocketServer server = RxSocketServer.Create(LogFactory); 96 | 97 | IRxSocketClient client = await server.LocalEndPoint.CreateRxSocketClientAsync(LogFactory); 98 | Task sendTask = Task.Run(() => client.Send(new byte[100_000_000])); 99 | await client.DisposeAsync(); 100 | await Assert.ThrowsAnyAsync(async () => await sendTask); 101 | await server.DisposeAsync(); 102 | } 103 | } 104 | 105 | -------------------------------------------------------------------------------- /RxSockets.Tests/Utility/Socket_Reader_Tests.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | namespace RxSockets.Tests; 3 | 4 | public sealed class Socket_Recieve_Tests(ITestOutputHelper output) : TestBase(output), IDisposable 5 | { 6 | private readonly Socket ServerSocket = Utilities.CreateSocket(); 7 | private readonly Socket Socket = Utilities.CreateSocket(); 8 | 9 | public void Dispose() 10 | { 11 | ServerSocket.Close(); 12 | Socket.Close(); 13 | } 14 | 15 | [Fact] 16 | public void T01_Disconnect() 17 | { 18 | IPEndPoint ipEndPoint = new(IPAddress.Loopback, 0); 19 | ServerSocket.Bind(ipEndPoint); 20 | ServerSocket.Listen(10); 21 | 22 | EndPoint endPoint = ServerSocket.LocalEndPoint ?? throw new InvalidOperationException("EndPoint"); 23 | Socket.Connect(endPoint); 24 | 25 | Socket accepted = ServerSocket.Accept(); 26 | accepted.Disconnect(false); 27 | 28 | byte[] buffer = new byte[10]; 29 | int bytes = Socket.Receive(buffer, SocketFlags.None); 30 | // after the remote socket disconnects, Socket.Receive() returns 0 bytes 31 | Assert.Equal(0, bytes); 32 | } 33 | 34 | [Fact] 35 | public async Task T02_Disconnect_ReceiveBytesAsync() 36 | { 37 | IPEndPoint ipEndPoint = new(IPAddress.Loopback, 0); 38 | ServerSocket.Bind(ipEndPoint); 39 | ServerSocket.Listen(10); 40 | 41 | EndPoint endPoint = ServerSocket.LocalEndPoint ?? throw new InvalidOperationException("EndPoint"); 42 | await Socket.ConnectAsync(endPoint); 43 | 44 | Socket accepted = await ServerSocket.AcceptAsync(); 45 | await accepted.DisconnectAsync(false); 46 | 47 | SocketReceiver reader = new(Socket, "?", Logger, default); 48 | 49 | // after the remote socket disconnects, reader.ReceiveByteAsync() returns nothing 50 | bool any = await reader.ReceiveAllAsync(default).AnyAsync(); 51 | Assert.False(any); 52 | } 53 | 54 | [Fact] 55 | public async Task T03_Disconnect_SocketReceiver() 56 | { 57 | IPEndPoint ipEndPoint = new(IPAddress.Loopback, 0); 58 | ServerSocket.Bind(ipEndPoint); 59 | ServerSocket.Listen(10); 60 | 61 | EndPoint endPoint = ServerSocket.LocalEndPoint ?? throw new InvalidOperationException("EndPoint"); 62 | await Socket.ConnectAsync(endPoint); 63 | Socket accepted = await ServerSocket.AcceptAsync(); 64 | 65 | SocketReceiver reader = new(Socket, "?", Logger, default); 66 | //var observable = reader.ReceiveObservable; 67 | System.Collections.Generic.IAsyncEnumerable xxx = reader.ReceiveAllAsync(default); 68 | 69 | accepted.Close(); 70 | 71 | // after the remote socket disconnects, the observable completes 72 | //var result = await observable.SingleOrDefaultAsync(); 73 | byte result = await xxx.SingleOrDefaultAsync(); 74 | 75 | Assert.Equal(0, result); // default 76 | } 77 | 78 | [Fact] 79 | public async Task T04_Disconnect_And_Send() 80 | { 81 | IPEndPoint ipEndPoint = new(IPAddress.Loopback, 0); 82 | ServerSocket.Bind(ipEndPoint); 83 | ServerSocket.Listen(10); 84 | 85 | EndPoint endPoint = ServerSocket.LocalEndPoint ?? throw new InvalidOperationException("EndPoint"); 86 | await Socket.ConnectAsync(endPoint); 87 | Socket accepted = await ServerSocket.AcceptAsync(); 88 | Assert.True(Socket.Connected); 89 | Assert.True(accepted.Connected); 90 | 91 | accepted.Close(); 92 | 93 | Socket.Send([1]); 94 | 95 | await Task.Yield(); 96 | 97 | // after the remote socket disconnects, Send() throws on second usage 98 | Assert.Throws(() => Socket.Send([1])); 99 | } 100 | 101 | [Fact] 102 | public async Task T05_Receive() 103 | { 104 | IPEndPoint ipEndPoint = new(IPAddress.Loopback, 0); 105 | ServerSocket.Bind(ipEndPoint); 106 | ServerSocket.Listen(10); 107 | 108 | EndPoint endPoint = ServerSocket.LocalEndPoint ?? throw new InvalidOperationException("EndPoint"); 109 | await Socket.ConnectAsync(endPoint); 110 | Socket accepted = await ServerSocket.AcceptAsync(); 111 | accepted.Send([1]); 112 | 113 | SocketReceiver reader = new(Socket, "?", Logger, default); 114 | System.Collections.Generic.IAsyncEnumerable xxx = reader.ReceiveAllAsync(default); 115 | byte result = await xxx.FirstAsync(); 116 | Assert.Equal(1, result); 117 | accepted.Close(); 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /RxSockets/Extensions/LengthPrefixExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using System.Reactive.Linq; 3 | namespace RxSockets; 4 | 5 | public static partial class Extension 6 | { 7 | /// 8 | /// Prepend a 4 byte payload length to a byte array. 9 | /// 10 | public static byte[] ToByteArrayWithLengthPrefix(this byte[] source) 11 | { 12 | ArgumentNullException.ThrowIfNull(source); 13 | 14 | byte[] buffer = new byte[source.Length + 4]; 15 | source.CopyTo(buffer, 4); 16 | EncodeMessageLength(buffer); 17 | return buffer; 18 | } 19 | 20 | ///////////////////////////////////////////////////////////////////// 21 | 22 | /// 23 | /// Transform a sequence of bytes with a length prefix into a sequence of byte arrays. 24 | /// 25 | public static IEnumerable ToArraysFromBytesWithLengthPrefix(this IEnumerable source) 26 | { 27 | ArgumentNullException.ThrowIfNull(source); 28 | 29 | int length = -1; 30 | using MemoryStream ms = new(); 31 | foreach (byte b in source) 32 | { 33 | ms.WriteByte(b); 34 | if (length == -1 && ms.Position == 4) 35 | { 36 | length = DecodeMessageLength(ms); 37 | ms.SetLength(0); 38 | } 39 | else if (length == ms.Length) 40 | { 41 | yield return ms.ToArray(); // array copy 42 | length = -1; 43 | ms.SetLength(0); 44 | } 45 | } 46 | if (ms.Position != 0) 47 | throw new InvalidDataException($"Invalid length: {length}."); 48 | } 49 | 50 | /// 51 | /// Transform a sequence of bytes with a length prefix into a sequence of byte arrays. 52 | /// 53 | public static async IAsyncEnumerable ToArraysFromBytesWithLengthPrefix(this IAsyncEnumerable source) 54 | { 55 | ArgumentNullException.ThrowIfNull(source); 56 | 57 | int length = -1; 58 | using MemoryStream ms = new(); 59 | await foreach (byte b in source.ConfigureAwait(false)) 60 | { 61 | ms.WriteByte(b); 62 | if (length == -1 && ms.Position == 4) 63 | { 64 | length = DecodeMessageLength(ms); 65 | ms.SetLength(0); 66 | } 67 | else if (length == ms.Length) 68 | { 69 | yield return ms.ToArray(); // array copy 70 | length = -1; 71 | ms.SetLength(0); 72 | } 73 | } 74 | if (ms.Position != 0) 75 | throw new InvalidDataException("ToArraysFromBytesWithLengthPrefix: invalid termination."); 76 | } 77 | 78 | /// 79 | /// Transform a sequence of bytes with a length prefix into a sequence of byte arrays. 80 | /// 81 | public static IObservable ToArraysFromBytesWithLengthPrefix(this IObservable source) 82 | { 83 | ArgumentNullException.ThrowIfNull(source); 84 | 85 | return Observable.Create(observer => 86 | { 87 | int length = -1; 88 | MemoryStream ms = new(); 89 | 90 | return source.Subscribe( 91 | onNext: b => 92 | { 93 | ms.WriteByte(b); 94 | if (length == -1 && ms.Position == 4) 95 | { 96 | length = DecodeMessageLength(ms); 97 | ms.SetLength(0); 98 | } 99 | else if (length == ms.Length) 100 | { 101 | observer.OnNext(ms.ToArray()); // array copy 102 | length = -1; 103 | ms.SetLength(0); 104 | } 105 | }, 106 | onError: (e) => 107 | { 108 | observer.OnError(e); 109 | ms.Dispose(); 110 | }, 111 | 112 | onCompleted: () => 113 | { 114 | if (ms.Position == 0) 115 | observer.OnCompleted(); 116 | else 117 | observer.OnError(new InvalidDataException("ToArraysFromBytesWithLengthPrefix: incomplete.")); 118 | ms.Dispose(); 119 | }); 120 | }); 121 | } 122 | 123 | // Encode 4 byte BigEndian integer length prefix. 124 | private static void EncodeMessageLength(byte[] buffer) 125 | { 126 | int length = buffer.Length - 4; 127 | int i = IPAddress.HostToNetworkOrder(length); 128 | if (!BitConverter.TryWriteBytes(buffer, i)) 129 | throw new InvalidDataException($"TryWriteBytes."); 130 | } 131 | 132 | private static int DecodeMessageLength(MemoryStream ms) 133 | { 134 | byte[] buffer = ms.GetBuffer(); 135 | int i = BitConverter.ToInt32(buffer, 0); 136 | int length = IPAddress.NetworkToHostOrder(i); 137 | if (length <= 0) 138 | throw new InvalidDataException($"Invalid length: {length}."); 139 | return length; 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /RxSockets.Tests/Tests/ClientServerTest.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging; 2 | using System.Diagnostics; 3 | using System.Threading; 4 | using System.Threading.Tasks; 5 | namespace RxSockets.Tests; 6 | 7 | public class ClientServerTest(ITestOutputHelper output) : TestBase(output) 8 | { 9 | [Fact] 10 | public async Task T01_HandshakeAsync() 11 | { 12 | IRxSocketServer server = RxSocketServer.Create(LogFactory); 13 | 14 | server.AcceptObservable 15 | .Select(acceptClient => Observable.FromAsync(async ct => 16 | { 17 | string message1 = await acceptClient.ReceiveAllAsync.ToStrings().FirstAsync(ct); 18 | Assert.Equal("Hello1FromClient", message1); 19 | 20 | acceptClient.Send(new[] { "Hello1FromServer" }.ToByteArray()); 21 | 22 | string[] messages = await acceptClient.ReceiveAllAsync.ToArraysFromBytesWithLengthPrefix().ToStringArrays().FirstAsync(ct); 23 | Assert.Equal("Hello2FromClient", messages[0]); 24 | 25 | acceptClient.Send(new[] { "Hello2FromServer" }.ToByteArray().ToByteArrayWithLengthPrefix()); 26 | 27 | acceptClient.Send(new[] { "Hello3FromServer" }.ToByteArray().ToByteArrayWithLengthPrefix()); 28 | })) 29 | .Concat() 30 | .Subscribe(); 31 | 32 | IRxSocketClient client = await server.LocalEndPoint.CreateRxSocketClientAsync(LogFactory); 33 | 34 | // Send the first message without prefix. 35 | client.Send("Hello1FromClient".ToByteArray()); 36 | 37 | // Receive the response message without prefix. 38 | string message1 = await client.ReceiveAllAsync.ToStrings().FirstAsync(); 39 | Assert.Equal("Hello1FromServer", message1); 40 | 41 | // Start sending and receiving messages with an int32 message length prefix. 42 | client.Send(new[] { "Hello2FromClient" }.ToByteArray().ToByteArrayWithLengthPrefix()); 43 | 44 | string[] message3 = await client.ReceiveAllAsync.ToArraysFromBytesWithLengthPrefix().ToStringArrays().FirstAsync(); 45 | Assert.Equal("Hello2FromServer", message3.Single()); 46 | 47 | client.ReceiveObservable 48 | .ToArraysFromBytesWithLengthPrefix() 49 | .ToStringArrays() 50 | .Subscribe(x => 51 | { 52 | Logger.LogInformation(x[0]); 53 | }); 54 | 55 | await Task.Delay(10); 56 | 57 | await client.DisposeAsync(); 58 | await server.DisposeAsync(); 59 | } 60 | 61 | [Fact] 62 | public async Task T01_HandshakeObservable() 63 | { 64 | IRxSocketServer server = RxSocketServer.Create(LogFactory); 65 | 66 | server.AcceptObservable 67 | .Select(acceptClient => Observable.FromAsync(async ct => 68 | { 69 | string message1 = await acceptClient.ReceiveAllAsync.ToStrings().FirstAsync(ct); 70 | //string message1 = await acceptClient.ReceiveObservable.ToStrings().FirstAsync(); 71 | Assert.Equal("Hello1FromClient", message1); 72 | 73 | acceptClient.Send(new[] { "Hello1FromServer" }.ToByteArray()); 74 | 75 | string[] messages = await acceptClient.ReceiveAllAsync.ToArraysFromBytesWithLengthPrefix().ToStringArrays().FirstAsync(ct); 76 | //string[] messages = await acceptClient.ReceiveObservable.ToArraysFromBytesWithLengthPrefix().ToStringArrays().FirstAsync(); 77 | Assert.Equal("Hello2FromClient", messages[0]); 78 | 79 | acceptClient.Send(new[] { "Hello2FromServer" }.ToByteArray().ToByteArrayWithLengthPrefix()); 80 | 81 | acceptClient.Send(new[] { "Hello3FromServer" }.ToByteArray().ToByteArrayWithLengthPrefix()); 82 | })) 83 | .Concat() 84 | .Subscribe(); 85 | 86 | IRxSocketClient client = await server.LocalEndPoint.CreateRxSocketClientAsync(LogFactory); 87 | 88 | // Send the first message without prefix. 89 | client.Send("Hello1FromClient".ToByteArray()); 90 | 91 | // Receive the response message without prefix. 92 | string message1 = await client.ReceiveAllAsync.ToStrings().FirstAsync(); 93 | //string message1 = await client.ReceiveObservable.ToStrings().FirstAsync(); 94 | Assert.Equal("Hello1FromServer", message1); 95 | 96 | // Start sending and receiving messages with an int32 message length prefix. 97 | client.Send(new[] { "Hello2FromClient" }.ToByteArray().ToByteArrayWithLengthPrefix()); 98 | 99 | string[] message3 = await client.ReceiveAllAsync.ToArraysFromBytesWithLengthPrefix().ToStringArrays().FirstAsync(); 100 | //string[] message3 = await client.ReceiveObservable.ToArraysFromBytesWithLengthPrefix().ToStringArrays().FirstAsync(); 101 | Assert.Equal("Hello2FromServer", message3.Single()); 102 | 103 | client.ReceiveObservable 104 | .ToArraysFromBytesWithLengthPrefix() 105 | .ToStringArrays() 106 | .Subscribe(x => 107 | { 108 | Debug.Assert(Thread.CurrentThread.IsBackground, "Not a background thread."); 109 | Logger.LogInformation("xxx"); 110 | }); 111 | 112 | await Task.Delay(10); 113 | 114 | await client.DisposeAsync(); 115 | await server.DisposeAsync(); 116 | 117 | } 118 | 119 | } 120 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | project.fragment.lock.json 46 | artifacts/ 47 | 48 | *_i.c 49 | *_p.c 50 | *_i.h 51 | *.ilk 52 | *.meta 53 | *.obj 54 | *.pch 55 | *.pdb 56 | *.pgc 57 | *.pgd 58 | *.rsp 59 | *.sbr 60 | *.tlb 61 | *.tli 62 | *.tlh 63 | *.tmp 64 | *.tmp_proj 65 | *.log 66 | *.vspscc 67 | *.vssscc 68 | .builds 69 | *.pidb 70 | *.svclog 71 | *.scc 72 | 73 | # Chutzpah Test files 74 | _Chutzpah* 75 | 76 | # Visual C++ cache files 77 | ipch/ 78 | *.aps 79 | *.ncb 80 | *.opendb 81 | *.opensdf 82 | *.sdf 83 | *.cachefile 84 | *.VC.db 85 | *.VC.VC.opendb 86 | 87 | # Visual Studio profiler 88 | *.psess 89 | *.vsp 90 | *.vspx 91 | *.sap 92 | 93 | # TFS 2012 Local Workspace 94 | $tf/ 95 | 96 | # Guidance Automation Toolkit 97 | *.gpState 98 | 99 | # ReSharper is a .NET coding add-in 100 | _ReSharper*/ 101 | *.[Rr]e[Ss]harper 102 | *.DotSettings.user 103 | 104 | # JustCode is a .NET coding add-in 105 | .JustCode 106 | 107 | # TeamCity is a build add-in 108 | _TeamCity* 109 | 110 | # DotCover is a Code Coverage Tool 111 | *.dotCover 112 | 113 | # NCrunch 114 | _NCrunch_* 115 | .*crunch*.local.xml 116 | nCrunchTemp_* 117 | 118 | # MightyMoose 119 | *.mm.* 120 | AutoTest.Net/ 121 | 122 | # Web workbench (sass) 123 | .sass-cache/ 124 | 125 | # Installshield output folder 126 | [Ee]xpress/ 127 | 128 | # DocProject is a documentation generator add-in 129 | DocProject/buildhelp/ 130 | DocProject/Help/*.HxT 131 | DocProject/Help/*.HxC 132 | DocProject/Help/*.hhc 133 | DocProject/Help/*.hhk 134 | DocProject/Help/*.hhp 135 | DocProject/Help/Html2 136 | DocProject/Help/html 137 | 138 | # Click-Once directory 139 | publish/ 140 | 141 | # Publish Web Output 142 | *.[Pp]ublish.xml 143 | *.azurePubxml 144 | # TODO: Comment the next line if you want to checkin your web deploy settings 145 | # but database connection strings (with potential passwords) will be unencrypted 146 | #*.pubxml 147 | *.publishproj 148 | 149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 150 | # checkin your Azure Web App publish settings, but sensitive information contained 151 | # in these scripts will be unencrypted 152 | PublishScripts/ 153 | 154 | # NuGet Packages 155 | *.nupkg 156 | # The packages folder can be ignored because of Package Restore 157 | **/packages/* 158 | # except build/, which is used as an MSBuild target. 159 | !**/packages/build/ 160 | # Uncomment if necessary however generally it will be regenerated when needed 161 | #!**/packages/repositories.config 162 | # NuGet v3's project.json files produces more ignoreable files 163 | *.nuget.props 164 | *.nuget.targets 165 | 166 | # Microsoft Azure Build Output 167 | csx/ 168 | *.build.csdef 169 | 170 | # Microsoft Azure Emulator 171 | ecf/ 172 | rcf/ 173 | 174 | # Windows Store app package directories and files 175 | AppPackages/ 176 | BundleArtifacts/ 177 | Package.StoreAssociation.xml 178 | _pkginfo.txt 179 | 180 | # Visual Studio cache files 181 | # files ending in .cache can be ignored 182 | *.[Cc]ache 183 | # but keep track of directories ending in .cache 184 | !*.[Cc]ache/ 185 | 186 | # Others 187 | ClientBin/ 188 | ~$* 189 | *~ 190 | *.dbmdl 191 | *.dbproj.schemaview 192 | *.jfm 193 | *.pfx 194 | *.publishsettings 195 | node_modules/ 196 | orleans.codegen.cs 197 | 198 | # Since there are multiple workflows, uncomment next line to ignore bower_components 199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 200 | #bower_components/ 201 | 202 | # RIA/Silverlight projects 203 | Generated_Code/ 204 | 205 | # Backup & report files from converting an old project file 206 | # to a newer Visual Studio version. Backup files are not needed, 207 | # because we have git ;-) 208 | _UpgradeReport_Files/ 209 | Backup*/ 210 | UpgradeLog*.XML 211 | UpgradeLog*.htm 212 | 213 | # SQL Server files 214 | *.mdf 215 | *.ldf 216 | 217 | # Business Intelligence projects 218 | *.rdl.data 219 | *.bim.layout 220 | *.bim_*.settings 221 | 222 | # Microsoft Fakes 223 | FakesAssemblies/ 224 | 225 | # GhostDoc plugin setting file 226 | *.GhostDoc.xml 227 | 228 | # Node.js Tools for Visual Studio 229 | .ntvs_analysis.dat 230 | 231 | # Visual Studio 6 build log 232 | *.plg 233 | 234 | # Visual Studio 6 workspace options file 235 | *.opt 236 | 237 | # Visual Studio LightSwitch build output 238 | **/*.HTMLClient/GeneratedArtifacts 239 | **/*.DesktopClient/GeneratedArtifacts 240 | **/*.DesktopClient/ModelManifest.xml 241 | **/*.Server/GeneratedArtifacts 242 | **/*.Server/ModelManifest.xml 243 | _Pvt_Extensions 244 | 245 | # Paket dependency manager 246 | .paket/paket.exe 247 | paket-files/ 248 | 249 | # FAKE - F# Make 250 | .fake/ 251 | 252 | # JetBrains Rider 253 | .idea/ 254 | *.sln.iml 255 | 256 | # CodeRush 257 | .cr/ 258 | 259 | # Python Tools for Visual Studio (PTVS) 260 | __pycache__/ 261 | *.pyc -------------------------------------------------------------------------------- /RxSockets.Tests/Examples/Examples.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Reactive.Threading.Tasks; 3 | using System.Threading; 4 | using System.Threading.Tasks; 5 | namespace RxSockets.Tests; 6 | 7 | public class Examples(ITestOutputHelper output) : TestBase(output) 8 | { 9 | [Fact] 10 | public async Task T00_Example() 11 | { 12 | // Create a socket server on an available port on the local host. 13 | IRxSocketServer server = RxSocketServer.Create(LogFactory); 14 | EndPoint endPoint = server.LocalEndPoint; 15 | 16 | // Start accepting connections from clients. 17 | server.AcceptObservable.Subscribe(acceptClient => 18 | { 19 | // After the server accepts a client connection... 20 | acceptClient.ReceiveObservable.ToStrings().Subscribe(onNext: message => 21 | { 22 | // Echo each message received back to the client. 23 | acceptClient.Send(message.ToByteArray()); 24 | }); 25 | }); 26 | 27 | // Create a socket client by first connecting to the server at the EndPoint. 28 | IRxSocketClient client = await endPoint.CreateRxSocketClientAsync(LogFactory); 29 | 30 | // Start receiving messages from the server. 31 | client.ReceiveObservable.ToStrings().Subscribe(onNext: message => 32 | { 33 | // The message received from the server is "Hello!". 34 | Assert.Equal("Hello!", message); 35 | }); 36 | 37 | // Send the message "Hello" to the server (which will be echoed back to the client). 38 | client.Send("Hello!".ToByteArray()); 39 | 40 | await Task.Delay(100); 41 | 42 | // Disconnect and dispose. 43 | await client.DisposeAsync(); 44 | await server.DisposeAsync(); 45 | } 46 | 47 | [Fact] 48 | public async Task T01_Send_And_Receive_String_Message() 49 | { 50 | IRxSocketServer server = RxSocketServer.Create(LogFactory); 51 | EndPoint endPoint = server.LocalEndPoint; 52 | 53 | // Start a task to allow the server to accept the next client connection. 54 | ValueTask acceptTask = server.AcceptAllAsync.FirstAsync(); 55 | 56 | // Create a socket client by successfully connecting to the server at EndPoint. 57 | IRxSocketClient client = await endPoint.CreateRxSocketClientAsync(LogFactory); 58 | 59 | // Get the client socket accepted by the server. 60 | IRxSocketClient accept = await acceptTask; 61 | Assert.True(accept.Connected && client.Connected); 62 | 63 | // start a task to receive the first string from the server. 64 | Task dataTask = client.ReceiveObservable.ToStrings().FirstAsync().ToTask(); 65 | 66 | // The server sends a string to the client. 67 | accept.Send("Welcome!".ToByteArray()); 68 | Assert.Equal("Welcome!", await dataTask); 69 | 70 | await client.DisposeAsync(); 71 | await server.DisposeAsync(); 72 | } 73 | 74 | [Fact] 75 | public async Task T10_Receive_Observable() 76 | { 77 | IRxSocketServer server = RxSocketServer.Create(LogFactory); 78 | EndPoint endPoint = server.LocalEndPoint; 79 | 80 | ValueTask acceptTask = server.AcceptAllAsync.FirstAsync(); 81 | IRxSocketClient client = await endPoint.CreateRxSocketClientAsync(LogFactory); 82 | IRxSocketClient accept = await acceptTask; 83 | 84 | IDisposable sub = client.ReceiveObservable.ToStrings().Subscribe(str => 85 | { 86 | Write(str); 87 | }); 88 | 89 | accept.Send("Welcome!".ToByteArray()); 90 | accept.Send("Welcome Again!".ToByteArray()); 91 | 92 | await Task.Delay(100); 93 | 94 | sub.Dispose(); 95 | 96 | await server.DisposeAsync(); 97 | await client.DisposeAsync(); 98 | } 99 | 100 | [Fact] 101 | public async Task T20_Accept_Observable() 102 | { 103 | string s = String.Create(10, 99, (span, state) => 104 | { 105 | span[1] = 's'; 106 | return; 107 | }); 108 | 109 | IRxSocketServer server = RxSocketServer.Create(LogFactory); 110 | EndPoint endPoint = server.LocalEndPoint; 111 | 112 | server.AcceptObservable 113 | .Subscribe(accepted => accepted.Send("Welcome!".ToByteArray())); 114 | 115 | IRxSocketClient client1 = await endPoint.CreateRxSocketClientAsync(LogFactory); 116 | IRxSocketClient client2 = await endPoint.CreateRxSocketClientAsync(LogFactory); 117 | IRxSocketClient client3 = await endPoint.CreateRxSocketClientAsync(LogFactory); 118 | 119 | Assert.Equal("Welcome!", await client1.ReceiveObservable.ToStrings().Take(1).FirstAsync()); 120 | Assert.Equal("Welcome!", await client2.ReceiveObservable.ToStrings().Take(1).FirstAsync()); 121 | Assert.Equal("Welcome!", await client3.ReceiveObservable.ToStrings().Take(1).FirstAsync()); 122 | 123 | await client1.DisposeAsync(); 124 | await client2.DisposeAsync(); 125 | await client3.DisposeAsync(); 126 | await server.DisposeAsync(); 127 | } 128 | 129 | [Fact] 130 | public async Task T30_Both() 131 | { 132 | IRxSocketServer server = RxSocketServer.Create(LogFactory); 133 | EndPoint endPoint = server.LocalEndPoint; 134 | 135 | server.AcceptObservable.Subscribe(accepted => 136 | { 137 | accepted.Send("Welcome!".ToByteArray()); 138 | accepted 139 | .ReceiveObservable 140 | .ToStrings() 141 | .Subscribe(s => accepted.Send(s.ToByteArray())); 142 | }); 143 | 144 | 145 | List clients = []; 146 | for (int i = 0; i < 3; i++) 147 | { 148 | IRxSocketClient client = await endPoint.CreateRxSocketClientAsync(LogFactory); 149 | client.Send("Hello".ToByteArray()); 150 | clients.Add(client); 151 | } 152 | 153 | foreach (IRxSocketClient client in clients) 154 | Assert.Equal("Hello", await client.ReceiveObservable.ToStrings().Skip(1).Take(1).FirstAsync()); 155 | 156 | foreach (IRxSocketClient client in clients) 157 | await client.DisposeAsync(); 158 | await server.DisposeAsync(); 159 | } 160 | 161 | [Fact] 162 | public async Task T40_Client_Disconnect() 163 | { 164 | SemaphoreSlim semaphore = new(0, 1); 165 | 166 | IRxSocketServer server = RxSocketServer.Create(LogFactory); 167 | EndPoint endPoint = server.LocalEndPoint; 168 | 169 | IRxSocketClient? acceptClient = null; 170 | server.AcceptObservable.Subscribe(ac => 171 | { 172 | acceptClient = ac; 173 | semaphore.Release(); 174 | acceptClient.ReceiveObservable.ToStrings().Subscribe(onNext: message => 175 | { 176 | acceptClient.Send(message.ToByteArray()); 177 | }); 178 | }); 179 | 180 | IRxSocketClient client = await endPoint.CreateRxSocketClientAsync(LogFactory); 181 | client.ReceiveObservable.ToStrings().Subscribe(onNext: message => 182 | { 183 | Write(message); 184 | }); 185 | 186 | client.Send("Hello!".ToByteArray()); 187 | 188 | await semaphore.WaitAsync(); 189 | if (acceptClient is null) 190 | throw new NullReferenceException(nameof(acceptClient)); 191 | 192 | await server.DisposeAsync(); 193 | await client.DisposeAsync(); 194 | 195 | semaphore.Dispose(); 196 | } 197 | 198 | [Fact] 199 | public async Task T41_Server_Disconnect() 200 | { 201 | SemaphoreSlim semaphore = new(0, 1); 202 | 203 | IRxSocketServer server = RxSocketServer.Create(LogFactory); 204 | EndPoint endPoint = server.LocalEndPoint; 205 | 206 | IRxSocketClient? acceptClient = null; 207 | server.AcceptObservable.Subscribe(ac => 208 | { 209 | acceptClient = ac; 210 | semaphore.Release(); 211 | acceptClient.ReceiveObservable.ToStrings().Subscribe(onNext: message => 212 | { 213 | acceptClient.Send(message.ToByteArray()); 214 | }); 215 | }); 216 | 217 | IRxSocketClient client = await endPoint.CreateRxSocketClientAsync(LogFactory); 218 | client.ReceiveObservable.ToStrings().Subscribe(onNext: message => 219 | { 220 | Write(message); 221 | }); 222 | 223 | client.Send("Hello!".ToByteArray()); 224 | await semaphore.WaitAsync(); 225 | if (acceptClient is null) 226 | throw new NullReferenceException(nameof(acceptClient)); 227 | 228 | await server.DisposeAsync(); 229 | await client.DisposeAsync(); 230 | } 231 | } 232 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------