From f4d97ba17d98a5e2a00e4b9d506b78391227be40 Mon Sep 17 00:00:00 2001 From: Kerry Jiang Date: Sat, 7 Dec 2024 23:33:40 -0800 Subject: [PATCH] added perf test --- test/SuperSocket.Tests/PerfTest.cs | 86 ++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 test/SuperSocket.Tests/PerfTest.cs diff --git a/test/SuperSocket.Tests/PerfTest.cs b/test/SuperSocket.Tests/PerfTest.cs new file mode 100644 index 000000000..6d7bc8ddd --- /dev/null +++ b/test/SuperSocket.Tests/PerfTest.cs @@ -0,0 +1,86 @@ +using System; +using System.IO; +using System.Linq; +using System.Net.Sockets; +using System.Threading; +using System.Threading.Tasks; +using SuperSocket.ProtoBase; +using SuperSocket.Server; +using SuperSocket.Server.Host; +using Xunit; +using Xunit.Abstractions; + +namespace SuperSocket.Tests +{ + public class PerfTest : TestClassBase + { + public PerfTest(ITestOutputHelper outputHelper) + : base(outputHelper) + { + } + + [Theory] + [InlineData(typeof(RegularHostConfigurator))] + [InlineData(typeof(SecureHostConfigurator))] + [InlineData(typeof(KestralConnectionHostConfigurator))] + public async Task ConcurrentSendReceive(Type hostConfiguratorType) + { + var hostConfigurator = CreateObject(hostConfiguratorType); + var connectionCount = 10; + var runTime = TimeSpan.FromMinutes(1); + + using (var server = CreateSocketServerBuilder(hostConfigurator) + .UsePackageHandler(async (s, p) => + { + await s.SendAsync(Utf8Encoding.GetBytes(p.Text + "\r\n")); + }).BuildAsServer()) + { + Assert.Equal("TestServer", server.Name); + + Assert.True(await server.StartAsync()); + OutputHelper.WriteLine("Started."); + + using var cancellationTokenSource = new CancellationTokenSource(); + + var tasks = Enumerable + .Range(0, connectionCount) + .Select(_ => RunConnectionAsync(hostConfigurator, cancellationTokenSource.Token)) + .ToArray(); + + cancellationTokenSource.CancelAfter(runTime); + + await Task.Delay(runTime); + + var rounds = await Task.WhenAll(tasks).WaitAsync(TimeSpan.FromSeconds(10)); + + OutputHelper.WriteLine($"Total rounds: {rounds.Sum()}."); + } + } + + private async Task RunConnectionAsync(IHostConfigurator hostConfigurator, CancellationToken cancellationToken) + { + var round = 0; + + using (var socket = hostConfigurator.CreateClient()) + using (var clientStream = await hostConfigurator.GetClientStream(socket)) + using (var streamReader = new StreamReader(clientStream, Utf8Encoding, true)) + using (var streamWriter = new StreamWriter(clientStream, Utf8Encoding, 1024 * 1024 * 4)) + { + while (!cancellationToken.IsCancellationRequested) + { + var text = Guid.NewGuid().ToString(); + + await streamWriter.WriteAsync($"{text}\r\n".AsMemory()); + await streamWriter.FlushAsync(); + + var line = await streamReader.ReadLineAsync(); + Assert.Equal(text, line); + + round++; + } + } + + return round; + } + } +} \ No newline at end of file