diff --git a/examples/UniNetty.Examples.Demo/DirectoryUtils.cs b/examples/UniNetty.Examples.Demo/DirectoryUtils.cs deleted file mode 100644 index 0b9d297..0000000 --- a/examples/UniNetty.Examples.Demo/DirectoryUtils.cs +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices; - -namespace UniNetty.Examples.Demo; - -public static class DirectoryUtils -{ - public static string SearchPath(string searchPath, int depth, out bool isDir) - { - isDir = false; - - for (int i = 0; i < depth; ++i) - { - var relativePath = string.Join("", Enumerable.Range(0, i).Select(x => "../")); - var searchingPath = Path.Combine(relativePath, searchPath); - var fullSearchingPath = Path.GetFullPath(searchingPath); - - if (File.Exists(fullSearchingPath)) - { - return fullSearchingPath; - } - - if (Directory.Exists(fullSearchingPath)) - { - isDir = true; - return fullSearchingPath; - } - } - - return string.Empty; - } - - // only directory - public static string SearchDirectory(string dirname, int depth = 10) - { - var searchingPath = SearchPath(dirname, depth, out var isDir); - if (isDir) - { - return searchingPath; - } - - var path = Path.GetDirectoryName(searchingPath) ?? string.Empty; - return path; - } - - public static string SearchFile(string filename, int depth = 10) - { - var searchingPath = SearchPath(filename, depth, out var isDir); - if (!isDir) - { - return searchingPath; - } - - return string.Empty; - } - - public static void OpenDirectory(string path) - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - Process.Start(new ProcessStartInfo - { - FileName = "explorer.exe", - Arguments = path, - UseShellExecute = true - }); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - Process.Start(new ProcessStartInfo - { - FileName = "open", - Arguments = path, - UseShellExecute = true - }); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - Process.Start(new ProcessStartInfo - { - FileName = "xdg-open", - Arguments = path, - UseShellExecute = true - }); - } - else - { - throw new NotSupportedException("Unsupported OS"); - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.Demo/Logging/DemoLogger.cs b/examples/UniNetty.Examples.Demo/Logging/DemoLogger.cs deleted file mode 100644 index 62deb4c..0000000 --- a/examples/UniNetty.Examples.Demo/Logging/DemoLogger.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; -using Serilog.Events; -using UniNetty.Logging; - -namespace UniNetty.Examples.Demo.Logging; - -public class DemoLogger : ILogger -{ - private readonly Serilog.ILogger _logger; - - public DemoLogger(Serilog.ILogger logger) - { - _logger = logger; - } - - public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) - { - var lv = FromLogLevel(logLevel); - //throw new NotImplementedException(); - _logger.Write(lv, state?.ToString() ?? string.Empty); - } - - public bool IsEnabled(LogLevel logLevel) - { - //throw new NotImplementedException(); - return true; - } - - public LogEventLevel FromLogLevel(LogLevel logLevel) - { - switch (logLevel) - { - case LogLevel.Trace: return LogEventLevel.Verbose; - case LogLevel.Debug: return LogEventLevel.Debug; - case LogLevel.Information: return LogEventLevel.Information; - case LogLevel.Warning: return LogEventLevel.Warning; - case LogLevel.Error: return LogEventLevel.Error; - case LogLevel.Critical: return LogEventLevel.Fatal; - case LogLevel.None: return LogEventLevel.Verbose; - } - - return LogEventLevel.Verbose; - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.Demo/Logging/DemoLoggerFactory.cs b/examples/UniNetty.Examples.Demo/Logging/DemoLoggerFactory.cs deleted file mode 100644 index ec0c53a..0000000 --- a/examples/UniNetty.Examples.Demo/Logging/DemoLoggerFactory.cs +++ /dev/null @@ -1,22 +0,0 @@ -using UniNetty.Logging; - -namespace UniNetty.Examples.Demo.Logging; - -public class DemoLoggerFactory : ILoggerFactory -{ - public ILogger CreateLogger(string categoryName) - { - var l = Serilog.Log.ForContext("Name", categoryName); - return new DemoLogger(l); - } - - public void AddProvider(ILoggerProvider provider) - { - // ... - } - - public void Dispose() - { - // ... - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.Demo/Logging/Sinks/LogMessageBrokerSink.cs b/examples/UniNetty.Examples.Demo/Logging/Sinks/LogMessageBrokerSink.cs deleted file mode 100644 index 15a75b2..0000000 --- a/examples/UniNetty.Examples.Demo/Logging/Sinks/LogMessageBrokerSink.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; -using System.IO; -using Serilog.Core; -using Serilog.Events; -using Serilog.Formatting; - -namespace UniNetty.Examples.Demo.Logging.Sinks; - -public class LogMessageBrokerSink : ILogEventSink -{ - public static event Action OnEmitted; - - private readonly ITextFormatter _formatter; - - public LogMessageBrokerSink(ITextFormatter formatter) - { - _formatter = formatter; - } - - public void Emit(LogEvent logEvent) - { - using var writer = new StringWriter(); - _formatter.Format(logEvent, writer); - OnEmitted?.Invoke((int)logEvent.Level, writer.ToString()); - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.Demo/Logging/Sinks/SerilogSinkExtensions.cs b/examples/UniNetty.Examples.Demo/Logging/Sinks/SerilogSinkExtensions.cs deleted file mode 100644 index d154ed1..0000000 --- a/examples/UniNetty.Examples.Demo/Logging/Sinks/SerilogSinkExtensions.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Serilog; -using Serilog.Configuration; -using Serilog.Events; -using Serilog.Formatting.Display; - -namespace UniNetty.Examples.Demo.Logging.Sinks; - -public static class SerilogSinkExtensions -{ - public static LoggerConfiguration LogMessageBroker( - this LoggerSinkConfiguration sinkConfiguration, - LogEventLevel restrictedToMinimumLevel = LogEventLevel.Verbose, - string outputTemplate = "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") - { - var formatter = new MessageTemplateTextFormatter(outputTemplate); - return sinkConfiguration.Sink(new LogMessageBrokerSink(formatter)); - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.Demo/Program.cs b/examples/UniNetty.Examples.Demo/Program.cs deleted file mode 100644 index 261684b..0000000 --- a/examples/UniNetty.Examples.Demo/Program.cs +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.IO; -using System.Security.Cryptography.X509Certificates; -using System.Threading; -using Serilog; -using UniNetty.Common.Internal.Logging; -using UniNetty.Examples.Demo.Logging; -using UniNetty.Examples.Demo.Logging.Sinks; -using UniNetty.Examples.DemoSupports; - -namespace UniNetty.Examples.Demo; - -public static class Program -{ - private static void InitializeLogger() - { - var format = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] {Message:lj} [{ThreadName}:{ThreadId}]{NewLine}{Exception}"; - Log.Logger = new LoggerConfiguration() - .MinimumLevel.Verbose() - .Enrich.WithThreadId() - .Enrich.WithThreadName() - .WriteTo.Async(c => c.LogMessageBroker(outputTemplate: format)) - .WriteTo.Async(c => c.Console(outputTemplate: format)) - .WriteTo.Async(c => c.File( - "logs/log.log", - rollingInterval: RollingInterval.Hour, - rollOnFileSizeLimit: true, - retainedFileCountLimit: null, - outputTemplate: format) - ) - .CreateLogger(); - - InternalLoggerFactory.DefaultFactory = new DemoLoggerFactory(); - } - - private static void InitializeWorkingDirectory() - { - var path = DirectoryUtils.SearchFile("LICENSE"); - if (!string.IsNullOrEmpty(path)) - { - var workingDirectory = Path.GetDirectoryName(path) ?? string.Empty; - workingDirectory = Path.GetFullPath(workingDirectory); - Directory.SetCurrentDirectory(workingDirectory); - } - } - - public static void Main(string[] args) - { - Thread.CurrentThread.Name ??= "main"; - InitializeWorkingDirectory(); - InitializeLogger(); - - var demo = new UniNettyDemo(); - demo.Initialize(); - demo.Start(); - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.Demo/UI/Canvas.cs b/examples/UniNetty.Examples.Demo/UI/Canvas.cs deleted file mode 100644 index b14c9a2..0000000 --- a/examples/UniNetty.Examples.Demo/UI/Canvas.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System.Collections.Immutable; -using System.Numerics; -using UniNetty.Examples.DemoSupports; - -namespace UniNetty.Examples.Demo.UI; - -public class Canvas -{ - public Vector2 Size; - private ImmutableArray _view; - - public readonly ExampleContext Context; - - public Canvas(ExampleContext context) - { - Context = context; - _view = ImmutableArray.Empty; - } - - public void ResetSize(Vector2 size) - { - Size = size; - } - - public void AddView(IView view) - { - _view = _view.Add(view); - } - - public void Update(double dt) - { - foreach (var view in _view) - { - view.Update(dt); - } - } - - - public void Draw(double dt) - { - foreach (var view in _view) - { - view.Draw(dt); - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.Demo/UI/ExamplesView.cs b/examples/UniNetty.Examples.Demo/UI/ExamplesView.cs deleted file mode 100644 index 393d479..0000000 --- a/examples/UniNetty.Examples.Demo/UI/ExamplesView.cs +++ /dev/null @@ -1,89 +0,0 @@ -using System; -using System.IO; -using System.Numerics; -using ImGuiNET; -using Serilog; -using UniNetty.Examples.DemoSupports; - -namespace UniNetty.Examples.Demo.UI; - -public class ExamplesView : IView -{ - private static readonly ILogger Logger = Log.ForContext(); - - private readonly Canvas _canvas; - private readonly ExamplesViewModel _vm; - - public ExamplesView(Canvas canvas) - { - _canvas = canvas; - _vm = new ExamplesViewModel(canvas.Context); - } - - public void Draw(double dt) - { - //ImGui.ShowDemoWindow(); - - ImGui.Begin("Examples"); - - // size reset - var rectSize = ImGui.GetItemRectSize(); - if (32 >= rectSize.X && 32 >= rectSize.Y) - { - int width = 310; - var posX = _canvas.Size.X - width; - //ImGui.SetWindowPos(new Vector2(posX, 0)); - ImGui.SetWindowSize(new Vector2(width, _canvas.Size.Y - 60)); - } - - foreach (var example in _vm.Examples) - { - if (null == example) - continue; - - var showSettings = ImGui.TreeNodeEx(example.Example.Name, ImGuiTreeNodeFlags.Bullet | ImGuiTreeNodeFlags.SpanFullWidth); - if (showSettings) - { - int port = example.Port; - if (ImGui.InputInt(" " + example.Example.Name + " Port", ref port)) ; - { - example.SetPort(port); - } - - // use size - if (0 != example.Size) - { - int size = example.Size; - if (ImGui.InputInt(" " + example.Example.Name + " Size", ref size)) - { - example.SetSize(size); - } - } - - var btnServer = example.IsRunningServer ? "Stop Server" : "Run Server"; - if (ImGui.Button(example.Example.Name + " " + btnServer)) - { - example.ToggleServer(); - } - - var btnClient = example.IsRunningClient ? "Stop Client" : "Run Client"; - if (ImGui.Button(example.Example.Name + " " + btnClient)) - { - example.ToggleClient(); - } - - - ImGui.TreePop(); - } - - ImGui.Separator(); // 구분선 - } - - ImGui.End(); - } - - public void Update(double dt) - { - - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.Demo/UI/ExamplesViewModel.cs b/examples/UniNetty.Examples.Demo/UI/ExamplesViewModel.cs deleted file mode 100644 index 40e02a8..0000000 --- a/examples/UniNetty.Examples.Demo/UI/ExamplesViewModel.cs +++ /dev/null @@ -1,90 +0,0 @@ -using System.Linq; -using UniNetty.Examples.DemoSupports; - -namespace UniNetty.Examples.Demo.UI; - -public class ExamplesViewModel -{ - public readonly ExampleSetting[] Examples; - - public ExamplesViewModel(ExampleContext context) - { - Examples = new ExampleSetting[ExampleType.Values.Count]; - - Examples[ExampleType.None.Index] = null; - - var ip = ExampleSupport.Shared.GetPrivateIp(); - - // Discard - var discard = new ExampleSetting(ExampleType.Discard); - discard.SetServer(context.RunDiscardServer); - discard.SetClient(context.RunDiscardClient); - discard.SetIp(ip); - discard.SetPort(8000); - discard.SetSize(256); - - // Echo - var echo = new ExampleSetting(ExampleType.Echo); - echo.SetServer(context.RunEchoServer); - echo.SetClient(context.RunEchoClient); - echo.SetIp(ip); - echo.SetPort(8010); - echo.SetSize(256); - - // Factorial - var factorial = new ExampleSetting(ExampleType.Factorial); - factorial.SetServer(context.RunFactorialServer); - factorial.SetClient(context.RunFactorialClient); - factorial.SetIp(ip); - factorial.SetPort(8020); - factorial.SetSize(256); - factorial.SetCount(100); - - // QuoteOfTheMoment - var quoteOfTheMoment = new ExampleSetting(ExampleType.QuoteOfTheMoment); - quoteOfTheMoment.SetServer(context.QuoteOfTheMomentServer); - quoteOfTheMoment.SetClient(context.RunQuoteOfTheMomentClient); - quoteOfTheMoment.SetIp(ip); - quoteOfTheMoment.SetPort(8030); - - // SecureChat - var secureChat = new ExampleSetting(ExampleType.SecureChat); - secureChat.SetServer(context.RunSecureChatServer); - secureChat.SetClient(context.RunSecureChatClient); - secureChat.SetIp(ip); - secureChat.SetPort(8040); - - // telnet - var telnet = new ExampleSetting(ExampleType.Telnet); - telnet.SetServer(context.RunTelnetServer); - telnet.SetClient(context.RunTelnetClient); - telnet.SetIp(ip); - telnet.SetPort(8050); - telnet.SetSize(256); - - var webSocket = new ExampleSetting(ExampleType.WebSocket); - webSocket.SetServer(context.RunWebSocketServer); - webSocket.SetClient(context.RunWebSocketClient); - webSocket.SetIp(ip); - webSocket.SetPort(8060); - webSocket.SetPath("/websocket"); - - // http - var http = new ExampleSetting(ExampleType.HttpServer); - http.SetServer(context.RunHelloHttpServer); - http.SetClient(context.RunHelloHttpClient); - http.SetIp(ip); - http.SetPort(8080); - - - // - Examples[ExampleType.Discard.Index] = discard; - Examples[ExampleType.Echo.Index] = echo; - Examples[ExampleType.Factorial.Index] = factorial; - Examples[ExampleType.QuoteOfTheMoment.Index] = quoteOfTheMoment; - Examples[ExampleType.SecureChat.Index] = secureChat; - Examples[ExampleType.Telnet.Index] = telnet; - Examples[ExampleType.WebSocket.Index] = webSocket; - Examples[ExampleType.HttpServer.Index] = http; - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.Demo/UI/IView.cs b/examples/UniNetty.Examples.Demo/UI/IView.cs deleted file mode 100644 index f897e15..0000000 --- a/examples/UniNetty.Examples.Demo/UI/IView.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace UniNetty.Examples.Demo.UI; - -public interface IView -{ - void Draw(double dt); - void Update(double dt); -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.Demo/UI/LogView.cs b/examples/UniNetty.Examples.Demo/UI/LogView.cs deleted file mode 100644 index a1c61c1..0000000 --- a/examples/UniNetty.Examples.Demo/UI/LogView.cs +++ /dev/null @@ -1,128 +0,0 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; -using System.Numerics; -using ImGuiNET; -using Serilog; -using UniNetty.Examples.Demo.Logging.Sinks; - -namespace UniNetty.Examples.Demo.UI; - -public class LogView : IView -{ - private static readonly ILogger Logger = Log.ForContext(); - - private Canvas _canvas; - - private readonly List _lines; - private readonly ConcurrentQueue _queues; - - - public LogView(Canvas canvas) - { - _canvas = canvas; - _lines = new(); - _queues = new(); - - LogMessageBrokerSink.OnEmitted += OnOut; - } - - private void OnOut(int level, string message) - { - var lines = message - .Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries) - .Select(x => new LogViewItem { Level = level, Message = x }); - - foreach (var line in lines) - { - _queues.Enqueue(line); - } - } - - public void Clear() - { - _lines.Clear(); - } - - public void Update(double dt) - { - while (_queues.TryDequeue(out var item)) - _lines.Add(item); - - // buffer - if (10240 < _lines.Count) - { - _lines.RemoveRange(0, _lines.Count - 8196); - } - } - - - public void Draw(double dt) - { - if (!ImGui.Begin("Log")) - { - ImGui.End(); - return; - } - - // size reset - var size = ImGui.GetItemRectSize(); - if (32 >= size.X && 32 >= size.Y) - { - int otherWidth = 310; - int height = 234; - var width = _canvas.Size.X - (otherWidth * 2); - //var posX = _canvas.Size.X - width; - // ImGui.SetNextWindowPos(new Vector2(otherWidth1, _canvas.Size.Y - height)); - ImGui.SetWindowSize(new Vector2(width, height)); - } - - - ImGui.PushStyleVar(ImGuiStyleVar.ScrollbarSize, 16.0f); - - if (ImGui.BeginChild("scrolling", Vector2.Zero, false, ImGuiWindowFlags.HorizontalScrollbar)) - { - //_isHovered = ImGui.IsWindowHovered(ImGuiHoveredFlags.RectOnly | ImGuiHoveredFlags.RootAndChildWindows); - - ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, Vector2.Zero); - - unsafe - { - var clipper = new ImGuiListClipperPtr(ImGuiNative.ImGuiListClipper_ImGuiListClipper()); - clipper.Begin(_lines.Count); - while (clipper.Step()) - { - for (int lineNo = clipper.DisplayStart; lineNo < clipper.DisplayEnd; lineNo++) - { - ImGui.TextUnformatted(_lines[lineNo].Message); - } - } - - clipper.End(); - clipper.Destroy(); - } - - ImGui.PopStyleVar(); - - // if (ImGui.GetScrollY() >= ImGui.GetScrollMaxY()) - // { - // ImGui.SetScrollHereY(1.0f); - // } - // 현재 스크롤 위치를 저장합니다. - float scrollY = ImGui.GetScrollY(); - float scrollMaxY = ImGui.GetScrollMaxY(); - - // 스크롤이 끝에 도달한 상태에서만 자동 스크롤을 수행하도록 합니다. - if (scrollY >= scrollMaxY - ImGui.GetWindowHeight() * 0.1f) - { - ImGui.SetScrollHereY(1.0f); - } - } - - ImGui.EndChild(); - ImGui.PopStyleVar(); - - ImGui.End(); - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.Demo/UI/LogViewItem.cs b/examples/UniNetty.Examples.Demo/UI/LogViewItem.cs deleted file mode 100644 index b41c6f1..0000000 --- a/examples/UniNetty.Examples.Demo/UI/LogViewItem.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace UniNetty.Examples.Demo.UI; - -public record LogViewItem -{ - public int Level; - public string Message; -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.Demo/UI/MenuView.cs b/examples/UniNetty.Examples.Demo/UI/MenuView.cs deleted file mode 100644 index a183e58..0000000 --- a/examples/UniNetty.Examples.Demo/UI/MenuView.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System.IO; -using ImGuiNET; -using Serilog; -using UniNetty.Examples.DemoSupports; - -namespace UniNetty.Examples.Demo.UI; - -public class MenuView : IView -{ - private static readonly ILogger Logger = Log.ForContext(); - - private readonly Canvas _canvas; - - public MenuView(Canvas canvas) - { - _canvas = canvas; - } - - public void Draw(double dt) - { - if (ImGui.BeginMainMenuBar()) - { - if (ImGui.BeginMenu("File")) - { - if (ImGui.MenuItem("Open In File Explorer")) - { - var currentDirectory = Directory.GetCurrentDirectory(); - DirectoryUtils.OpenDirectory(currentDirectory); - } - - ImGui.EndMenu(); - } - - if (ImGui.BeginMenu("Help")) - { - if (ImGui.MenuItem("Repository")) - { - ExampleSupport.Shared.OpenUrl("https://github.com/ikpil/UniNetty"); - } - - if (ImGui.MenuItem("Nuget")) - { - ExampleSupport.Shared.OpenUrl("https://www.nuget.org/packages/UniNetty.Common/"); - } - - ImGui.Separator(); - if (ImGui.MenuItem("Issue Tracker")) - { - ExampleSupport.Shared.OpenUrl("https://github.com/ikpil/UniNetty/issues"); - } - - if (ImGui.MenuItem("Release Notes")) - { - ExampleSupport.Shared.OpenUrl("https://github.com/ikpil/UniNetty/blob/main/CHANGELOG.md"); - } - - ImGui.EndMenu(); - } - - ImGui.EndMainMenuBar(); - } - } - - public void Update(double dt) - { - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.Demo/UniNetty.Examples.Demo.csproj b/examples/UniNetty.Examples.Demo/UniNetty.Examples.Demo.csproj deleted file mode 100644 index 8871b6d..0000000 --- a/examples/UniNetty.Examples.Demo/UniNetty.Examples.Demo.csproj +++ /dev/null @@ -1,34 +0,0 @@ - - - - Exe - net6.0;net8.0 - false - true - true - - - - - PreserveNewest - resources\%(Filename)%(Extension) - - - - - - - - - - - - - - - - - - - - diff --git a/examples/UniNetty.Examples.Demo/UniNettyDemo.cs b/examples/UniNetty.Examples.Demo/UniNettyDemo.cs deleted file mode 100644 index 32a2ea6..0000000 --- a/examples/UniNetty.Examples.Demo/UniNettyDemo.cs +++ /dev/null @@ -1,206 +0,0 @@ -using System; -using System.Collections.Immutable; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Numerics; -using System.Runtime; -using System.Runtime.InteropServices; -using System.Security.Cryptography.X509Certificates; -using ImGuiNET; -using Serilog; -using Silk.NET.Input; -using Silk.NET.Maths; -using Silk.NET.OpenGL; -using Silk.NET.OpenGL.Extensions.ImGui; -using Silk.NET.Windowing; -using UniNetty.Common; -using UniNetty.Common.Internal.Logging; -using UniNetty.Examples.Demo.UI; -using UniNetty.Examples.DemoSupports; - -namespace UniNetty.Examples.Demo; - -public class UniNettyDemo -{ - private static readonly IInternalLogger Logger = InternalLoggerFactory.GetInstance(); - - private ExampleContext _context; - private IWindow _window; - private GL _gl; - private IInputContext _input; - private ImGuiController _imgui; - - private int[] _viewport; - private Vector2D _resolution; - private int _width = 1000; - private int _height = 900; - - private Canvas _canvas; - - public void Initialize() - { - Logger.Info("initializing..."); - - // load pfx - var pfx = Path.Combine(AppContext.BaseDirectory, "resources", "uninetty.com.pfx"); - var cert = new X509Certificate2(pfx, "password"); - - var context = new ExampleContext(); - context.SetCertificate(cert); - - _context = context; - } - - public void Start() - { - Logger.Info("starting..."); - - var monitor = Window.Platforms.First().GetMainMonitor(); - var resolution = monitor.VideoMode.Resolution.Value; - - float aspect = 16.0f / 9.0f; - _width = Math.Min(resolution.X, (int)(resolution.Y * aspect)) - 100; - _height = resolution.Y - 100; - _viewport = new int[] { 0, 0, _width, _height }; - - var options = WindowOptions.Default; - options.Title = "UniNetty Demo"; - options.Size = new Vector2D(_width, _height); - options.Position = new Vector2D((resolution.X - _width) / 2, (resolution.Y - _height) / 2); - options.VSync = true; - options.ShouldSwapAutomatically = false; - options.PreferredDepthBufferBits = 24; - _window = Window.Create(options); - - if (_window == null) - { - throw new Exception("Failed to create the GLFW window"); - } - - ResourceLeakDetector.Level = ResourceLeakDetector.DetectionLevel.Disabled; - - _window.Closing += OnWindowClosing; - _window.Load += OnWindowOnLoad; - _window.Resize += OnWindowResize; - _window.FramebufferResize += OnWindowFramebufferSizeChanged; - _window.Update += OnWindowUpdate; - _window.Render += OnWindowRender; - - _window.Run(); - - // context.RunWebSocketServer(); - // context.RunTelnetServer(); - // context.RunSecureChatServer(); - // context.QuoteOfTheMomentServer(); - // context.RunHelloHttpServer(); - // context.RunFactorialServer(); - // context.RunEchoServer(); - // context.RunDiscardServer(); - // - // context.RunWebSocketClient(); - // context.RunTelentClient(); - // context.RunSecureChatClient(); - // context.RunQuoteOfTheMomentClient(); - // context.RunFactorialClient(); - // context.RunEchoClient(); - } - - private void OnWindowClosing() - { - } - - private void OnWindowResize(Vector2D size) - { - _width = size.X; - _height = size.Y; - } - - private void OnWindowFramebufferSizeChanged(Vector2D size) - { - _gl.Viewport(size); - _viewport = new int[] { 0, 0, _width, _height }; - _canvas.ResetSize(new Vector2(_width, _height)); - } - - private void OnWindowOnLoad() - { - _input = _window.CreateInput(); - _gl = _window.CreateOpenGL(); - - var scale = (float)_resolution.X / 1920; - int fontSize = Math.Max(24, (int)(24 * scale)); - var fontPath = Path.Combine(AppContext.BaseDirectory, "resources", "Roboto-Regular.ttf"); - - // for windows : Microsoft Visual C++ Redistributable Package - // link - https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist - var imGuiFontConfig = new ImGuiFontConfig(fontPath, fontSize, null); - _imgui = new ImGuiController(_gl, _window, _input, imGuiFontConfig); - - var style = ImGui.GetStyle(); - style.ScaleAllSizes(scale); - style.FramePadding = new Vector2(4, 4); - style.ItemSpacing = new Vector2(4, 4); - // style.CellPadding = new Vector2(10, 10); - style.WindowPadding = new Vector2(10, 10); - //ImGui.GetIO().FontGlobalScale = 2.0f; - - _canvas = new Canvas(_context); - _canvas.ResetSize(new Vector2(_width, _height)); - _canvas.AddView(new MenuView(_canvas)); - _canvas.AddView(new ExamplesView(_canvas)); - _canvas.AddView(new LogView(_canvas)); - - var vendor = _gl.GetStringS(GLEnum.Vendor); - var version = _gl.GetStringS(GLEnum.Version); - var rendererGl = _gl.GetStringS(GLEnum.Renderer); - var glslString = _gl.GetStringS(GLEnum.ShadingLanguageVersion); - var currentCulture = CultureInfo.CurrentCulture; - string bitness = Environment.Is64BitOperatingSystem ? "64-bit" : "32-bit"; - - var workingDirectory = Directory.GetCurrentDirectory(); - Logger.Info($"Working directory - {workingDirectory}"); - - Logger.Info($"{RuntimeInformation.OSArchitecture} {RuntimeInformation.OSDescription}"); - Logger.Info($"{RuntimeInformation.ProcessArchitecture} {RuntimeInformation.FrameworkDescription}"); - Logger.Info($"Processor Count : {Environment.ProcessorCount}"); - Logger.Info("Transport type : Socket"); - - Logger.Info($"Server garbage collection : {(GCSettings.IsServerGC ? "Enabled" : "Disabled")}"); - Logger.Info($"Current latency mode for garbage collection: {GCSettings.LatencyMode}"); - Logger.Info(""); - - Logger.Info($"ImGui.Net - version({ImGui.GetVersion()}) UI scale({scale}) fontSize({fontSize})"); - Logger.Info($"Dotnet - {Environment.Version.ToString()} culture({currentCulture.Name})"); - Logger.Info($"OS Version - {Environment.OSVersion} {bitness}"); - Logger.Info($"{vendor} {rendererGl}"); - Logger.Info($"gl version({version}) lang version({glslString})"); - } - - private void OnWindowUpdate(double dt) - { - var io = ImGui.GetIO(); - - io.DisplaySize = new Vector2(_width, _height); - io.DisplayFramebufferScale = Vector2.One; - io.DeltaTime = (float)dt; - - _canvas.Update(dt); - _imgui.Update((float)dt); - } - - private void OnWindowRender(double dt) - { - _gl.ClearColor(0.3f, 0.3f, 0.32f, 1.0f); - _gl.Clear((uint)GLEnum.ColorBufferBit | (uint)GLEnum.DepthBufferBit); - _gl.Enable(GLEnum.Blend); - _gl.BlendFunc(GLEnum.SrcAlpha, GLEnum.OneMinusSrcAlpha); - _gl.Disable(GLEnum.Texture2D); - _gl.Enable(GLEnum.DepthTest); - _gl.Enable(GLEnum.CullFace); - - _canvas.Draw(dt); - _imgui.Render(); - _window.SwapBuffers(); - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.DemoSupports/AnonymousDisposer.cs b/examples/UniNetty.Examples.DemoSupports/AnonymousDisposer.cs deleted file mode 100644 index 1699d61..0000000 --- a/examples/UniNetty.Examples.DemoSupports/AnonymousDisposer.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System; - -namespace UniNetty.Examples.DemoSupports -{ - internal class AnonymousDisposer : IDisposable - { - private Action _action; - private bool _disposed; - private readonly object _lock = new object(); - - public static IDisposable Create(Action action) - { - return new AnonymousDisposer(action); - } - - private AnonymousDisposer(Action action) - { - _action = action ?? throw new ArgumentNullException(nameof(action)); - } - - ~AnonymousDisposer() - { - Dispose(false); - } - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - protected virtual void Dispose(bool disposing) - { - bool needToDispose = false; - lock (_lock) - { - if (!_disposed) - { - needToDispose = true; - _disposed = true; - } - } - - if (needToDispose) - { - var temp = _action; - _action = null; - temp.Invoke(); - } - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.DemoSupports/ExampleContext.cs b/examples/UniNetty.Examples.DemoSupports/ExampleContext.cs deleted file mode 100644 index 9bbfd29..0000000 --- a/examples/UniNetty.Examples.DemoSupports/ExampleContext.cs +++ /dev/null @@ -1,210 +0,0 @@ -using System; -using System.Net; -using System.Security.Cryptography.X509Certificates; -using UniNetty.Common.Internal.Logging; -using UniNetty.Examples.Discard.Client; -using UniNetty.Examples.Discard.Server; -using UniNetty.Examples.Echo.Client; -using UniNetty.Examples.Echo.Server; -using UniNetty.Examples.Factorial.Client; -using UniNetty.Examples.Factorial.Server; -using UniNetty.Examples.HttpServer; -using UniNetty.Examples.QuoteOfTheMoment.Client; -using UniNetty.Examples.QuoteOfTheMoment.Server; -using UniNetty.Examples.SecureChat.Client; -using UniNetty.Examples.SecureChat.Server; -using UniNetty.Examples.Telnet.Client; -using UniNetty.Examples.Telnet.Server; -using UniNetty.Examples.WebSockets.Client; -using UniNetty.Examples.WebSockets.Server; - -namespace UniNetty.Examples.DemoSupports -{ - public class ExampleContext - { - public X509Certificate2 Cert { get; private set; } - - public void SetCertificate(X509Certificate2 cert) - { - Cert = cert; - } - - // discard - public IDisposable RunDiscardServer(ExampleSetting setting) - { - var server = new DiscardServer(); - _ = server.StartAsync(Cert, setting.Port); - - return AnonymousDisposer.Create(() => - { - _ = server.StopAsync(); - }); - } - - public IDisposable RunDiscardClient(ExampleSetting setting) - { - var client = new DiscardClient(); - _ = client.StartAsync(Cert, IPAddress.Parse(setting.Ip), setting.Port, setting.Size); - - return AnonymousDisposer.Create(() => - { - _ = client.StopAsync(); - }); - } - - - // echo - public IDisposable RunEchoServer(ExampleSetting setting) - { - var server = new EchoServer(); - _ = server.StartAsync(Cert, setting.Port); - - return AnonymousDisposer.Create(() => - { - _ = server.StopAsync(); - }); - } - - public IDisposable RunEchoClient(ExampleSetting setting) - { - var client = new EchoClient(); - _ = client.StartAsync(Cert, IPAddress.Parse(setting.Ip), setting.Port, setting.Size); - return AnonymousDisposer.Create(() => - { - _ = client.StopAsync(); - }); - } - - // factorial - public IDisposable RunFactorialServer(ExampleSetting setting) - { - var server = new FactorialServer(); - _ = server.StartAsync(Cert, setting.Port); - - return AnonymousDisposer.Create(() => - { - _ = server.StopAsync(); - }); - } - - public IDisposable RunFactorialClient(ExampleSetting setting) - { - var client = new FactorialClient(); - _ = client.StartAsync(Cert, IPAddress.Parse(setting.Ip), setting.Port, setting.Count); - - - return AnonymousDisposer.Create(() => - { - _ = client.StopAsync(); - }); - } - - // QuoteOfTheMoment - public IDisposable QuoteOfTheMomentServer(ExampleSetting setting) - { - var server = new QuoteOfTheMomentServer(); - _ = server.StartAsync(setting.Port); - return AnonymousDisposer.Create(() => - { - _ = server.StopAsync(); - }); - } - - public IDisposable RunQuoteOfTheMomentClient(ExampleSetting setting) - { - var client = new QuoteOfTheMomentClient(); - _ = client.StartAsync(setting.Port); - - return AnonymousDisposer.Create(() => - { - _ = client.StopAsync(); - }); - } - - // secure - public IDisposable RunSecureChatServer(ExampleSetting setting) - { - var server = new SecureChatServer(); - _ = server.StartAsync(Cert, setting.Port); - return AnonymousDisposer.Create(() => - { - _ = server.StopAsync(); - }); - } - - public IDisposable RunSecureChatClient(ExampleSetting setting) - { - var client = new SecureChatClient(); - _ = client.StartAsync(Cert, IPAddress.Parse(setting.Ip), setting.Port); - return AnonymousDisposer.Create(() => - { - _ = client.StopAsync(); - }); - } - - // - public IDisposable RunTelnetServer(ExampleSetting setting) - { - var server = new TelnetServer(); - _ = server.StartAsync(Cert, setting.Port); - - return AnonymousDisposer.Create(() => - { - _ = server.StopAsync(); - }); - } - - - public IDisposable RunTelnetClient(ExampleSetting setting) - { - var client = new TelnetClient(); - _ = client.StartAsync(Cert, IPAddress.Parse(setting.Ip), setting.Port); - return AnonymousDisposer.Create(() => - { - _ = client.StopAsync(); - }); - } - - - // websocket - public IDisposable RunWebSocketServer(ExampleSetting setting) - { - var server = new WebSocketServer(); - _ = server.StartAsync(Cert, setting.Port); - return AnonymousDisposer.Create(() => - { - _ = server.StopAsync(); - }); - } - - public IDisposable RunWebSocketClient(ExampleSetting setting) - { - var client = new WebSocketClient(); - _ = client.StartAsync(Cert, IPAddress.Parse(setting.Ip), setting.Port, setting.Path); - - return AnonymousDisposer.Create(() => - { - _ = client.StopAsync(); - }); - } - - // http - public IDisposable RunHelloHttpServer(ExampleSetting setting) - { - var server = new HelloHttpServer(); - _ = server.StartAsync(Cert, setting.Port); - - return AnonymousDisposer.Create(() => - { - _ = server.StopAsync(); - }); - } - - public IDisposable RunHelloHttpClient(ExampleSetting setting) - { - ExampleSupport.Shared.OpenUrl($"https://{setting.Ip}:{setting.Port}/json"); - - return null; - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.DemoSupports/ExampleSetting.cs b/examples/UniNetty.Examples.DemoSupports/ExampleSetting.cs deleted file mode 100644 index 82cf947..0000000 --- a/examples/UniNetty.Examples.DemoSupports/ExampleSetting.cs +++ /dev/null @@ -1,89 +0,0 @@ -using System; - -namespace UniNetty.Examples.DemoSupports -{ - public class ExampleSetting - { - public readonly ExampleType Example; - - public string Ip { get; private set; } - public int Port { get; private set; } - public int Size { get; private set; } - public int Count { get; private set; } - public string Path { get; private set; } - - public bool IsRunningServer => null != _stopServer; - private Func _runServer; - private IDisposable _stopServer; - - public bool IsRunningClient => null != _stopClient; - private Func _runClient; - private IDisposable _stopClient; - - public ExampleSetting(ExampleType example) - { - Example = example; - } - - public void SetServer(Func runServer) - { - _runServer = runServer; - } - - public void SetClient(Func runClient) - { - _runClient = runClient; - } - - public void SetIp(string ip) - { - Ip = ip; - } - - public void SetPort(int port) - { - Port = port; - } - - public void SetSize(int size) - { - Size = size; - } - - public void SetCount(int count) - { - Count = count; - } - - public void SetPath(string path) - { - Path = path; - } - - public void ToggleServer() - { - if (null == _stopServer) - { - _stopServer = _runServer?.Invoke(this); - } - else - { - _stopServer.Dispose(); - _stopServer = null; - } - } - - public void ToggleClient() - { - if (null == _stopClient) - { - _stopClient = _runClient?.Invoke(this); - } - else - { - _stopClient.Dispose(); - _stopClient = null; - } - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.DemoSupports/ExampleSupport.cs b/examples/UniNetty.Examples.DemoSupports/ExampleSupport.cs deleted file mode 100644 index 030b535..0000000 --- a/examples/UniNetty.Examples.DemoSupports/ExampleSupport.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System; -using System.Diagnostics; -using System.Net; -using System.Net.Sockets; -using System.Runtime.InteropServices; -using UniNetty.Common.Internal.Logging; - -namespace UniNetty.Examples.DemoSupports -{ - public class ExampleSupport - { - private static readonly IInternalLogger Logger = InternalLoggerFactory.GetInstance(); - - public static readonly ExampleSupport Shared = new ExampleSupport(); - - public void OpenUrl(string url) - { - try - { - // OS에 따라 다른 명령 실행 - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - var psi = new ProcessStartInfo("cmd", $"/c start {url}") { CreateNoWindow = true }; - Process.Start(psi); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - Process.Start("open", url); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - Process.Start("xdg-open", url); - } - } - catch (Exception ex) - { - Logger.Info($"Error opening web browser: {ex.Message}"); - } - } - - public string GetPrivateIp() - { - var host = Dns.GetHostEntry(Dns.GetHostName()); - foreach (var ip in host.AddressList) - { - if (ip.AddressFamily == AddressFamily.InterNetwork) - { - return ip.ToString(); - } - } - - return string.Empty; - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.DemoSupports/ExampleType.cs b/examples/UniNetty.Examples.DemoSupports/ExampleType.cs deleted file mode 100644 index ed618d6..0000000 --- a/examples/UniNetty.Examples.DemoSupports/ExampleType.cs +++ /dev/null @@ -1,53 +0,0 @@ -using UniNetty.Common.Collections.Immutable; - -namespace UniNetty.Examples.DemoSupports -{ - /* - * { - "ssl": "false", - "host": "127.0.0.1", - "port": "8080", - "path": "/websocket", - "size": "256", - "count": "100", - "Logging": { - "LogLevel": { - "Default": "Trace" - } - } -} - */ - public class ExampleType - { - public static readonly ExampleType None = new ExampleType(0, nameof(None)); - public static readonly ExampleType Discard = new ExampleType(1, nameof(Discard)); - public static readonly ExampleType Echo = new ExampleType(2, nameof(Echo)); - public static readonly ExampleType Factorial = new ExampleType(3, nameof(Factorial)); - public static readonly ExampleType HttpServer = new ExampleType(4, nameof(HttpServer)); - public static readonly ExampleType QuoteOfTheMoment = new ExampleType(5, nameof(QuoteOfTheMoment)); - public static readonly ExampleType SecureChat = new ExampleType(6, nameof(SecureChat)); - public static readonly ExampleType Telnet = new ExampleType(7, nameof(Telnet)); - public static readonly ExampleType WebSocket = new ExampleType(8, nameof(WebSocket)); - - public static readonly UniImmutableArray Values = UniImmutableArrays.CreateRange( - None, - Discard, - Echo, - Factorial, - HttpServer, - QuoteOfTheMoment, - SecureChat, - Telnet, - WebSocket - ); - - public readonly int Index; - public readonly string Name; - - private ExampleType(int index, string name) - { - Index = index; - Name = name; - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.DemoSupports/UniNetty.Examples.DemoSupports.csproj b/examples/UniNetty.Examples.DemoSupports/UniNetty.Examples.DemoSupports.csproj deleted file mode 100644 index cde9076..0000000 --- a/examples/UniNetty.Examples.DemoSupports/UniNetty.Examples.DemoSupports.csproj +++ /dev/null @@ -1,25 +0,0 @@ - - - netstandard2.1;net6.0;net8.0 - false - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/UniNetty.Examples.Discard.Client/DiscardClient.cs b/examples/UniNetty.Examples.Discard.Client/DiscardClient.cs deleted file mode 100644 index 68dcc62..0000000 --- a/examples/UniNetty.Examples.Discard.Client/DiscardClient.cs +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.IO; -using System.Net; -using System.Net.Security; -using System.Net.Sockets; -using System.Security.Cryptography.X509Certificates; -using System.Threading.Tasks; -using UniNetty.Handlers.Logging; -using UniNetty.Handlers.Tls; -using UniNetty.Transport.Bootstrapping; -using UniNetty.Transport.Channels; -using UniNetty.Transport.Channels.Sockets; - -namespace UniNetty.Examples.Discard.Client -{ - public class DiscardClient - { - private MultithreadEventLoopGroup _group; - private IChannel _channel; - - public async Task StartAsync(X509Certificate2 cert, IPAddress host, int port, int size) - { - _group = new MultithreadEventLoopGroup(); - - string targetHost = null; - if (null != cert) - { - targetHost = cert.GetNameInfo(X509NameType.DnsName, false); - } - - var bootstrap = new Bootstrap(); - bootstrap - .Group(_group) - .Channel() - .Option(ChannelOption.TcpNodelay, true) - .Handler(new ActionChannelInitializer(channel => - { - IChannelPipeline pipeline = channel.Pipeline; - - if (cert != null) - { - pipeline.AddLast(new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost))); - } - - pipeline.AddLast(new LoggingHandler()); - pipeline.AddLast(new DiscardClientHandler(size)); - })); - - _channel = await bootstrap.ConnectAsync(new IPEndPoint(host, port)); - } - - public async Task StopAsync() - { - await _channel.CloseAsync(); - await _group.ShutdownGracefullyAsync(); - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.Discard.Client/DiscardClientHandler.cs b/examples/UniNetty.Examples.Discard.Client/DiscardClientHandler.cs deleted file mode 100644 index f8921ab..0000000 --- a/examples/UniNetty.Examples.Discard.Client/DiscardClientHandler.cs +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System.Threading.Tasks; -using UniNetty.Common.Internal.Logging; - -namespace UniNetty.Examples.Discard.Client -{ - using System; - using UniNetty.Buffers; - using UniNetty.Transport.Channels; - - public class DiscardClientHandler : SimpleChannelInboundHandler - { - private static readonly IInternalLogger Logger = InternalLoggerFactory.GetInstance(); - - private Random _random; - private IChannelHandlerContext ctx; - private byte[] array; - private int _size; - - public DiscardClientHandler(int size) - { - _random = new Random((int)DateTime.UtcNow.Ticks); - _size = size; - } - - public override void ChannelActive(IChannelHandlerContext ctx) - { - this.array = new byte[_size]; - this.ctx = ctx; - - // Send the initial messages. - this.GenerateTraffic(); - } - - protected override void ChannelRead0(IChannelHandlerContext context, object message) - { - // Server is supposed to send nothing, but if it sends something, discard it. - } - - public override void ExceptionCaught(IChannelHandlerContext ctx, Exception e) - { - Logger.Info("{0}", e.ToString()); - this.ctx.CloseAsync(); - } - - - async void GenerateTraffic() - { - try - { - - lock (_random) - { - _random.NextBytes(array); - } - - IByteBuffer buffer = Unpooled.WrappedBuffer(this.array); - // Flush the outbound buffer to the socket. - // Once flushed, generate the same amount of traffic again. - await this.ctx.WriteAndFlushAsync(buffer); - await Task.Delay(1000); - this.GenerateTraffic(); - } - catch - { - await this.ctx.CloseAsync(); - } - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.Discard.Client/UniNetty.Examples.Discard.Client.csproj b/examples/UniNetty.Examples.Discard.Client/UniNetty.Examples.Discard.Client.csproj deleted file mode 100644 index 8a6a550..0000000 --- a/examples/UniNetty.Examples.Discard.Client/UniNetty.Examples.Discard.Client.csproj +++ /dev/null @@ -1,10 +0,0 @@ - - - netstandard2.1;net6.0;net8.0 - false - - - - - - \ No newline at end of file diff --git a/examples/UniNetty.Examples.Discard.Server/DiscardServer.cs b/examples/UniNetty.Examples.Discard.Server/DiscardServer.cs deleted file mode 100644 index 24544d9..0000000 --- a/examples/UniNetty.Examples.Discard.Server/DiscardServer.cs +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Security.Cryptography.X509Certificates; -using System.Threading.Tasks; -using UniNetty.Common.Internal.Logging; -using UniNetty.Handlers.Logging; -using UniNetty.Handlers.Tls; -using UniNetty.Transport.Bootstrapping; -using UniNetty.Transport.Channels; -using UniNetty.Transport.Channels.Sockets; - -namespace UniNetty.Examples.Discard.Server -{ - public class DiscardServer - { - private static readonly IInternalLogger Logger = InternalLoggerFactory.GetInstance(); - - private MultithreadEventLoopGroup _bossGroup; - private MultithreadEventLoopGroup _workerGroup; - private IChannel _listen; - - public async Task StartAsync(X509Certificate2 cert, int port) - { - Logger.Info($"Starting discard server at port {port}"); - - _bossGroup = new MultithreadEventLoopGroup(1); - _workerGroup = new MultithreadEventLoopGroup(); - - try - { - var bootstrap = new ServerBootstrap() - .Group(_bossGroup, _workerGroup) - .Channel() - .Option(ChannelOption.SoBacklog, 100) - .Handler(new LoggingHandler("LSTN")) - .ChildHandler(new ActionChannelInitializer(channel => - { - IChannelPipeline pipeline = channel.Pipeline; - if (null != cert) - { - pipeline.AddLast(TlsHandler.Server(cert)); - } - - pipeline.AddLast(new LoggingHandler("CONN")); - pipeline.AddLast(new DiscardServerHandler()); - })); - - _listen = await bootstrap.BindAsync(port); - Logger.Info($"Listening on port {port}"); - } - catch (Exception e) - { - Logger.Error(e); - } - } - - public async Task StopAsync() - { - if (null == _listen) - return; - - Logger.Info("Stopping discard server"); - try - { - await _listen.CloseAsync(); - _listen = null; - } - catch (Exception e) - { - Logger.Error(e); - } - finally - { - await Task.WhenAll(_bossGroup.ShutdownGracefullyAsync(), _workerGroup.ShutdownGracefullyAsync()); - _bossGroup = null; - _workerGroup = null; - - Logger.Info("Stopped discard server"); - } - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.Discard.Server/DiscardServerHandler.cs b/examples/UniNetty.Examples.Discard.Server/DiscardServerHandler.cs deleted file mode 100644 index b1cab68..0000000 --- a/examples/UniNetty.Examples.Discard.Server/DiscardServerHandler.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using UniNetty.Common.Internal.Logging; - -namespace UniNetty.Examples.Discard.Server -{ - - using System; - using UniNetty.Transport.Channels; - - public class DiscardServerHandler : SimpleChannelInboundHandler - { - private static readonly IInternalLogger Logger = InternalLoggerFactory.GetInstance(); - - protected override void ChannelRead0(IChannelHandlerContext context, object message) - { - } - - public override void ExceptionCaught(IChannelHandlerContext ctx, Exception e) - { - Logger.Info("{0}", e.ToString()); - ctx.CloseAsync(); - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.Discard.Server/UniNetty.Examples.Discard.Server.csproj b/examples/UniNetty.Examples.Discard.Server/UniNetty.Examples.Discard.Server.csproj deleted file mode 100644 index 8a54170..0000000 --- a/examples/UniNetty.Examples.Discard.Server/UniNetty.Examples.Discard.Server.csproj +++ /dev/null @@ -1,10 +0,0 @@ - - - netstandard2.1;net6.0;net8.0 - false - - - - - - \ No newline at end of file diff --git a/examples/UniNetty.Examples.Echo.Client/EchoClient.cs b/examples/UniNetty.Examples.Echo.Client/EchoClient.cs deleted file mode 100644 index 252a1d8..0000000 --- a/examples/UniNetty.Examples.Echo.Client/EchoClient.cs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Net; -using System.Net.Security; -using System.Security.Cryptography.X509Certificates; -using System.Threading.Tasks; -using UniNetty.Codecs; -using UniNetty.Handlers.Logging; -using UniNetty.Handlers.Tls; -using UniNetty.Transport.Bootstrapping; -using UniNetty.Transport.Channels; -using UniNetty.Transport.Channels.Sockets; - -namespace UniNetty.Examples.Echo.Client -{ - public class EchoClient - { - private MultithreadEventLoopGroup _group; - private IChannel _channel; - - public async Task StartAsync(X509Certificate2 cert, IPAddress host, int port, int size) - { - _group = new MultithreadEventLoopGroup(); - var bootstrap = new Bootstrap(); - bootstrap - .Group(_group) - .Channel() - .Option(ChannelOption.TcpNodelay, true) - .Handler(new ActionChannelInitializer(channel => - { - IChannelPipeline pipeline = channel.Pipeline; - - if (cert != null) - { - var targetHost = cert.GetNameInfo(X509NameType.DnsName, false); - pipeline.AddLast("tls", new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost))); - } - - pipeline.AddLast(new LoggingHandler()); - pipeline.AddLast("framing-enc", new LengthFieldPrepender(2)); - pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2)); - - pipeline.AddLast("echo", new EchoClientHandler(size)); - })); - - _channel = await bootstrap.ConnectAsync(new IPEndPoint(host, port)); - } - - public async Task StopAsync() - { - await _channel.CloseAsync(); - await _group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)); - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.Echo.Client/EchoClientHandler.cs b/examples/UniNetty.Examples.Echo.Client/EchoClientHandler.cs deleted file mode 100644 index 4a6dd1f..0000000 --- a/examples/UniNetty.Examples.Echo.Client/EchoClientHandler.cs +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using UniNetty.Common.Internal.Logging; - -namespace UniNetty.Examples.Echo.Client -{ - using System; - using System.Text; - using UniNetty.Buffers; - using UniNetty.Transport.Channels; - - public class EchoClientHandler : ChannelHandlerAdapter - { - private static readonly IInternalLogger Logger = InternalLoggerFactory.GetInstance(); - - private readonly IByteBuffer initialMessage; - private int _size; - - public EchoClientHandler(int size) - { - _size = size; - this.initialMessage = Unpooled.Buffer(size); - byte[] messageBytes = Encoding.UTF8.GetBytes("Hello world"); - this.initialMessage.WriteBytes(messageBytes); - } - - public override void ChannelActive(IChannelHandlerContext context) => context.WriteAndFlushAsync(this.initialMessage); - - public override void ChannelRead(IChannelHandlerContext context, object message) - { - var byteBuffer = message as IByteBuffer; - if (byteBuffer != null) - { - Logger.Info("Received from server: " + byteBuffer.ToString(Encoding.UTF8)); - } - - context.WriteAsync(message); - } - - public override void ChannelReadComplete(IChannelHandlerContext context) => context.Flush(); - - public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) - { - Logger.Info("Exception: " + exception); - context.CloseAsync(); - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.Echo.Client/UniNetty.Examples.Echo.Client.csproj b/examples/UniNetty.Examples.Echo.Client/UniNetty.Examples.Echo.Client.csproj deleted file mode 100644 index 8a54170..0000000 --- a/examples/UniNetty.Examples.Echo.Client/UniNetty.Examples.Echo.Client.csproj +++ /dev/null @@ -1,10 +0,0 @@ - - - netstandard2.1;net6.0;net8.0 - false - - - - - - \ No newline at end of file diff --git a/examples/UniNetty.Examples.Echo.Server/EchoServer.cs b/examples/UniNetty.Examples.Echo.Server/EchoServer.cs deleted file mode 100644 index f201a82..0000000 --- a/examples/UniNetty.Examples.Echo.Server/EchoServer.cs +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Security.Cryptography.X509Certificates; -using System.Threading.Tasks; -using UniNetty.Codecs; -using UniNetty.Handlers.Logging; -using UniNetty.Handlers.Tls; -using UniNetty.Transport.Bootstrapping; -using UniNetty.Transport.Channels; -using UniNetty.Transport.Channels.Sockets; - -namespace UniNetty.Examples.Echo.Server -{ - public class EchoServer - { - private MultithreadEventLoopGroup _bossGroup; - private MultithreadEventLoopGroup _workerGroup; - private IChannel _channel; - - public async Task StartAsync(X509Certificate2 cert, int port) - { - _bossGroup = new MultithreadEventLoopGroup(1); - _workerGroup = new MultithreadEventLoopGroup(); - - var bootstrap = new ServerBootstrap(); - bootstrap.Group(_bossGroup, _workerGroup); - bootstrap.Channel(); - - bootstrap - .Option(ChannelOption.SoBacklog, 100) - .Handler(new LoggingHandler("SRV-LSTN")) - .ChildHandler(new ActionChannelInitializer(channel => - { - IChannelPipeline pipeline = channel.Pipeline; - if (cert != null) - { - pipeline.AddLast("tls", TlsHandler.Server(cert)); - } - - pipeline.AddLast(new LoggingHandler("SRV-CONN")); - pipeline.AddLast("framing-enc", new LengthFieldPrepender(2)); - pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2)); - - pipeline.AddLast("echo", new EchoServerHandler()); - })); - - _channel = await bootstrap.BindAsync(port); - } - - public async Task StopAsync() - { - await _channel.CloseAsync(); - await Task.WhenAll( - _bossGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)), - _workerGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1))); - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.Echo.Server/EchoServerHandler.cs b/examples/UniNetty.Examples.Echo.Server/EchoServerHandler.cs deleted file mode 100644 index b68dacd..0000000 --- a/examples/UniNetty.Examples.Echo.Server/EchoServerHandler.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using UniNetty.Common.Internal.Logging; - -namespace UniNetty.Examples.Echo.Server -{ - using System; - using System.Text; - using UniNetty.Buffers; - using UniNetty.Transport.Channels; - - public class EchoServerHandler : ChannelHandlerAdapter - { - private static readonly IInternalLogger Logger = InternalLoggerFactory.GetInstance(); - - public override void ChannelRead(IChannelHandlerContext context, object message) - { - var buffer = message as IByteBuffer; - if (buffer != null) - { - Logger.Info("Received from client: " + buffer.ToString(Encoding.UTF8)); - } - - context.WriteAsync(message); - } - - public override void ChannelReadComplete(IChannelHandlerContext context) => context.Flush(); - - public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) - { - Logger.Info("Exception: " + exception); - context.CloseAsync(); - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.Echo.Server/UniNetty.Examples.Echo.Server.csproj b/examples/UniNetty.Examples.Echo.Server/UniNetty.Examples.Echo.Server.csproj deleted file mode 100644 index 8a54170..0000000 --- a/examples/UniNetty.Examples.Echo.Server/UniNetty.Examples.Echo.Server.csproj +++ /dev/null @@ -1,10 +0,0 @@ - - - netstandard2.1;net6.0;net8.0 - false - - - - - - \ No newline at end of file diff --git a/examples/UniNetty.Examples.Factorial.Client/FactorialClient.cs b/examples/UniNetty.Examples.Factorial.Client/FactorialClient.cs deleted file mode 100644 index cd0f260..0000000 --- a/examples/UniNetty.Examples.Factorial.Client/FactorialClient.cs +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Net; -using System.Net.Security; -using System.Security.Cryptography.X509Certificates; -using System.Threading.Tasks; -using UniNetty.Common.Internal.Logging; -using UniNetty.Handlers.Logging; -using UniNetty.Handlers.Tls; -using UniNetty.Transport.Bootstrapping; -using UniNetty.Transport.Channels; -using UniNetty.Transport.Channels.Sockets; - -namespace UniNetty.Examples.Factorial.Client -{ - public class FactorialClient - { - private static readonly IInternalLogger Logger = InternalLoggerFactory.GetInstance(); - - private MultithreadEventLoopGroup _group; - private IChannel _channel; - - public async Task StartAsync(X509Certificate2 cert, IPAddress host, int port, int count) - { - _group = new MultithreadEventLoopGroup(); - - var bootstrap = new Bootstrap(); - bootstrap - .Group(_group) - .Channel() - .Option(ChannelOption.TcpNodelay, true) - .Handler(new ActionChannelInitializer(channel => - { - IChannelPipeline pipeline = channel.Pipeline; - - if (cert != null) - { - var targetHost = cert.GetNameInfo(X509NameType.DnsName, false); - pipeline.AddLast(new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost))); - } - - pipeline.AddLast(new LoggingHandler("CONN")); - pipeline.AddLast(new BigIntegerDecoder()); - pipeline.AddLast(new NumberEncoder()); - pipeline.AddLast(new FactorialClientHandler(count)); - })); - - _channel = await bootstrap.ConnectAsync(new IPEndPoint(host, port)); - - // Get the handler instance to retrieve the answer. - var handler = (FactorialClientHandler)_channel.Pipeline.Last(); - - // Print out the answer. - Logger.Info("Factorial of {0} is: {1}", count.ToString(), handler.GetFactorial().ToString()); - } - - public async Task StopAsync() - { - await _channel.CloseAsync(); - await _group.ShutdownGracefullyAsync(); - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.Factorial.Client/FactorialClientHandler.cs b/examples/UniNetty.Examples.Factorial.Client/FactorialClientHandler.cs deleted file mode 100644 index 4a49b1c..0000000 --- a/examples/UniNetty.Examples.Factorial.Client/FactorialClientHandler.cs +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -namespace UniNetty.Examples.Factorial.Client -{ - using System.Collections.Concurrent; - using System.Numerics; - using UniNetty.Transport.Channels; - - public class FactorialClientHandler : SimpleChannelInboundHandler - { - private int _count; - IChannelHandlerContext ctx; - int receivedMessages; - int next = 1; - readonly BlockingCollection answer = new BlockingCollection(); - - public FactorialClientHandler(int count) - { - _count = count; - } - - - public BigInteger GetFactorial() => this.answer.Take(); - - public override void ChannelActive(IChannelHandlerContext ctx) - { - this.ctx = ctx; - this.SendNumbers(); - } - - protected override void ChannelRead0(IChannelHandlerContext ctx, BigInteger msg) - { - this.receivedMessages++; - if (this.receivedMessages == _count) - { - ctx.CloseAsync().ContinueWith(t => this.answer.Add(msg)); - } - } - - void SendNumbers() - { - for (int i = 0; (i < 4096) && (this.next <= _count); i++) - { - this.ctx.WriteAsync(new BigInteger(this.next)); - this.next++; - } - this.ctx.Flush(); - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.Factorial.Client/UniNetty.Examples.Factorial.Client.csproj b/examples/UniNetty.Examples.Factorial.Client/UniNetty.Examples.Factorial.Client.csproj deleted file mode 100644 index a0c979a..0000000 --- a/examples/UniNetty.Examples.Factorial.Client/UniNetty.Examples.Factorial.Client.csproj +++ /dev/null @@ -1,12 +0,0 @@ - - - netstandard2.1;net6.0;net8.0 - false - - - - - - - - \ No newline at end of file diff --git a/examples/UniNetty.Examples.Factorial.Server/FactorialServer.cs b/examples/UniNetty.Examples.Factorial.Server/FactorialServer.cs deleted file mode 100644 index e63f7bd..0000000 --- a/examples/UniNetty.Examples.Factorial.Server/FactorialServer.cs +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Security.Cryptography.X509Certificates; -using System.Threading.Tasks; -using UniNetty.Handlers.Logging; -using UniNetty.Handlers.Tls; -using UniNetty.Transport.Bootstrapping; -using UniNetty.Transport.Channels; -using UniNetty.Transport.Channels.Sockets; - -namespace UniNetty.Examples.Factorial.Server -{ - public class FactorialServer - { - private MultithreadEventLoopGroup _bossGroup; - private MultithreadEventLoopGroup _workerGroup; - private IChannel _channel; - - public async Task StartAsync(X509Certificate2 cert, int port) - { - _bossGroup = new MultithreadEventLoopGroup(1); - _workerGroup = new MultithreadEventLoopGroup(); - var bootstrap = new ServerBootstrap(); - bootstrap - .Group(_bossGroup, _workerGroup) - .Channel() - .Option(ChannelOption.SoBacklog, 100) - .Handler(new LoggingHandler("LSTN")) - .ChildHandler(new ActionChannelInitializer(channel => - { - IChannelPipeline pipeline = channel.Pipeline; - if (cert != null) - { - pipeline.AddLast(TlsHandler.Server(cert)); - } - - pipeline.AddLast(new LoggingHandler("CONN")); - pipeline.AddLast(new NumberEncoder(), new BigIntegerDecoder(), new FactorialServerHandler()); - })); - - _channel = await bootstrap.BindAsync(port); - } - - public async Task StopAsync() - { - await _channel.CloseAsync(); - await Task.WhenAll(_bossGroup.ShutdownGracefullyAsync(), _workerGroup.ShutdownGracefullyAsync()); - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.Factorial.Server/FactorialServerHandler.cs b/examples/UniNetty.Examples.Factorial.Server/FactorialServerHandler.cs deleted file mode 100644 index fb7e7b6..0000000 --- a/examples/UniNetty.Examples.Factorial.Server/FactorialServerHandler.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using UniNetty.Common.Internal.Logging; - -namespace UniNetty.Examples.Factorial.Server -{ - using System; - using System.Numerics; - using UniNetty.Transport.Channels; - - public class FactorialServerHandler : SimpleChannelInboundHandler - { - private static readonly IInternalLogger Logger = InternalLoggerFactory.GetInstance(); - - BigInteger lastMultiplier = new BigInteger(1); - BigInteger factorial = new BigInteger(1); - - protected override void ChannelRead0(IChannelHandlerContext ctx, BigInteger msg) - { - this.lastMultiplier = msg; - this.factorial *= msg; - ctx.WriteAndFlushAsync(this.factorial); - } - - public override void ChannelInactive(IChannelHandlerContext ctx) => Logger.Info("UniNetty.Examples.Factorial of {0} is: {1}", this.lastMultiplier, this.factorial); - - public override void ExceptionCaught(IChannelHandlerContext ctx, Exception e) => ctx.CloseAsync(); - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.Factorial.Server/UniNetty.Examples.Factorial.Server.csproj b/examples/UniNetty.Examples.Factorial.Server/UniNetty.Examples.Factorial.Server.csproj deleted file mode 100644 index f9056fe..0000000 --- a/examples/UniNetty.Examples.Factorial.Server/UniNetty.Examples.Factorial.Server.csproj +++ /dev/null @@ -1,11 +0,0 @@ - - - netstandard2.1;net6.0;net8.0 - false - - - - - - - \ No newline at end of file diff --git a/examples/UniNetty.Examples.Factorial/BigIntegerDecoder.cs b/examples/UniNetty.Examples.Factorial/BigIntegerDecoder.cs deleted file mode 100644 index 0c145ed..0000000 --- a/examples/UniNetty.Examples.Factorial/BigIntegerDecoder.cs +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -namespace UniNetty.Examples.Factorial -{ - - using System; - using System.Collections.Generic; - using System.Numerics; - using UniNetty.Buffers; - using UniNetty.Codecs; - using UniNetty.Transport.Channels; - - public class BigIntegerDecoder : ByteToMessageDecoder - { - public override void Decode(IChannelHandlerContext context, IByteBuffer input, List output) - { - if (input.ReadableBytes < 5) - { - return; - } - - input.MarkReaderIndex(); - - int magicNumber = input.ReadByte(); - if (magicNumber != 'F') - { - input.ResetReaderIndex(); - throw new Exception("Invalid magic number: " + magicNumber); - } - - int dataLength = input.ReadInt(); - if (input.ReadableBytes < dataLength) - { - input.ResetReaderIndex(); - return; - } - - var decoded = new byte[dataLength]; - input.ReadBytes(decoded); - - output.Add(new BigInteger(decoded)); - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.Factorial/NumberEncoder.cs b/examples/UniNetty.Examples.Factorial/NumberEncoder.cs deleted file mode 100644 index 453797d..0000000 --- a/examples/UniNetty.Examples.Factorial/NumberEncoder.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System.Numerics; - -namespace UniNetty.Examples.Factorial -{ - using System.Collections.Generic; - using UniNetty.Buffers; - using UniNetty.Codecs; - using UniNetty.Transport.Channels; - - public class NumberEncoder : MessageToMessageEncoder - { - public override void Encode(IChannelHandlerContext context, BigInteger message, List output) - { - IByteBuffer buffer = context.Allocator.Buffer(); - - //https://msdn.microsoft.com/en-us/library/BigInteger.tobytearray(v=vs.110).aspx - //BigInteger.ToByteArray() return a Little-Endian bytes - //IByteBuffer is Big-Endian by default - byte[] data = message.ToByteArray(); - buffer.WriteByte((byte)'F'); - buffer.WriteInt(data.Length); - buffer.WriteBytes(data); - output.Add(buffer); - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.Factorial/UniNetty.Examples.Factorial.csproj b/examples/UniNetty.Examples.Factorial/UniNetty.Examples.Factorial.csproj deleted file mode 100644 index 4f4582e..0000000 --- a/examples/UniNetty.Examples.Factorial/UniNetty.Examples.Factorial.csproj +++ /dev/null @@ -1,9 +0,0 @@ - - - netstandard2.1;net6.0;net8.0 - - - - - - \ No newline at end of file diff --git a/examples/UniNetty.Examples.HttpServer/HelloHttpServer.cs b/examples/UniNetty.Examples.HttpServer/HelloHttpServer.cs deleted file mode 100644 index 80cfa8e..0000000 --- a/examples/UniNetty.Examples.HttpServer/HelloHttpServer.cs +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Security.Cryptography.X509Certificates; -using System.Threading.Tasks; -using UniNetty.Codecs.Http; -using UniNetty.Common.Internal.Logging; -using UniNetty.Handlers.Tls; -using UniNetty.Transport.Bootstrapping; -using UniNetty.Transport.Channels; -using UniNetty.Transport.Channels.Sockets; - -namespace UniNetty.Examples.HttpServer -{ - public class HelloHttpServer - { - private static readonly IInternalLogger Logger = InternalLoggerFactory.GetInstance(); - - private MultithreadEventLoopGroup _group; - private MultithreadEventLoopGroup _workGroup; - private IChannel _channel; - - public async Task StartAsync(X509Certificate2 cert, int port) - { - _group = new MultithreadEventLoopGroup(1); - _workGroup = new MultithreadEventLoopGroup(); - - var bootstrap = new ServerBootstrap(); - bootstrap.Group(_group, _workGroup); - bootstrap.Channel(); - - bootstrap - .Option(ChannelOption.SoBacklog, 8192) - .ChildHandler(new ActionChannelInitializer(channel => - { - IChannelPipeline pipeline = channel.Pipeline; - if (cert != null) - { - pipeline.AddLast(TlsHandler.Server(cert)); - } - - pipeline.AddLast("encoder", new HttpResponseEncoder()); - pipeline.AddLast("decoder", new HttpRequestDecoder(4096, 8192, 8192, false)); - pipeline.AddLast("handler", new HelloHttpServerHandler()); - })); - - _channel = await bootstrap.BindAsync(port); - - Logger.Info($"Open your web browser and navigate to "); - Logger.Info($"{(null != cert ? "https" : "http")}://127.0.0.1:{port}/plaintext"); - Logger.Info($"{(null != cert ? "https" : "http")}://127.0.0.1:{port}/json"); - } - - public async Task StopAsync() - { - await _channel.CloseAsync(); - await _group.ShutdownGracefullyAsync(); - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.HttpServer/HelloHttpServerHandler.cs b/examples/UniNetty.Examples.HttpServer/HelloHttpServerHandler.cs deleted file mode 100644 index 6b9f3af..0000000 --- a/examples/UniNetty.Examples.HttpServer/HelloHttpServerHandler.cs +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -namespace UniNetty.Examples.HttpServer -{ - using System.Text; - using UniNetty.Buffers; - using UniNetty.Codecs.Http; - using UniNetty.Common.Utilities; - using UniNetty.Transport.Channels; - using System; - using UniNetty.Common; - - sealed class HelloHttpServerHandler : ChannelHandlerAdapter - { - static readonly ThreadLocalCache Cache = new ThreadLocalCache(); - - sealed class ThreadLocalCache : FastThreadLocal - { - protected override AsciiString GetInitialValue() - { - DateTime dateTime = DateTime.UtcNow; - return AsciiString.Cached($"{dateTime.DayOfWeek}, {dateTime:dd MMM yyyy HH:mm:ss z}"); - } - } - - static readonly byte[] StaticPlaintext = Encoding.UTF8.GetBytes("Hello, World!"); - static readonly int StaticPlaintextLen = StaticPlaintext.Length; - static readonly IByteBuffer PlaintextContentBuffer = Unpooled.UnreleasableBuffer(Unpooled.DirectBuffer().WriteBytes(StaticPlaintext)); - static readonly AsciiString PlaintextClheaderValue = AsciiString.Cached($"{StaticPlaintextLen}"); - static readonly AsciiString JsonClheaderValue = AsciiString.Cached($"{JsonLen()}"); - - static readonly AsciiString TypePlain = AsciiString.Cached("text/plain"); - static readonly AsciiString TypeJson = AsciiString.Cached("application/json"); - static readonly AsciiString ServerName = AsciiString.Cached("Netty"); - static readonly AsciiString ContentTypeEntity = HttpHeaderNames.ContentType; - static readonly AsciiString DateEntity = HttpHeaderNames.Date; - static readonly AsciiString ContentLengthEntity = HttpHeaderNames.ContentLength; - static readonly AsciiString ServerEntity = HttpHeaderNames.Server; - - volatile ICharSequence date = Cache.Value; - - static int JsonLen() => Encoding.UTF8.GetBytes(NewMessage().ToJsonFormat()).Length; - - static MessageBody NewMessage() => new MessageBody("Hello, World!"); - - public override void ChannelRead(IChannelHandlerContext ctx, object message) - { - if (message is IHttpRequest request) - { - try - { - this.Process(ctx, request); - } - finally - { - ReferenceCountUtil.Release(message); - } - } - else - { - ctx.FireChannelRead(message); - } - } - - void Process(IChannelHandlerContext ctx, IHttpRequest request) - { - string uri = request.Uri; - switch (uri) - { - case "/plaintext": - this.WriteResponse(ctx, PlaintextContentBuffer.Duplicate(), TypePlain, PlaintextClheaderValue); - break; - case "/json": - byte[] json = Encoding.UTF8.GetBytes(NewMessage().ToJsonFormat()); - this.WriteResponse(ctx, Unpooled.WrappedBuffer(json), TypeJson, JsonClheaderValue); - break; - default: - var response = new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.NotFound, Unpooled.Empty, false); - ctx.WriteAndFlushAsync(response); - ctx.CloseAsync(); - break; - } - } - - void WriteResponse(IChannelHandlerContext ctx, IByteBuffer buf, ICharSequence contentType, ICharSequence contentLength) - { - // Build the response object. - var response = new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.OK, buf, false); - HttpHeaders headers = response.Headers; - headers.Set(ContentTypeEntity, contentType); - headers.Set(ServerEntity, ServerName); - headers.Set(DateEntity, this.date); - headers.Set(ContentLengthEntity, contentLength); - - // Close the non-keep-alive connection after the write operation is done. - ctx.WriteAsync(response); - } - - public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) => context.CloseAsync(); - - public override void ChannelReadComplete(IChannelHandlerContext context) => context.Flush(); - } -} diff --git a/examples/UniNetty.Examples.HttpServer/MessageBody.cs b/examples/UniNetty.Examples.HttpServer/MessageBody.cs deleted file mode 100644 index 1bb3b84..0000000 --- a/examples/UniNetty.Examples.HttpServer/MessageBody.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -namespace UniNetty.Examples.HttpServer -{ - sealed class MessageBody - { - public MessageBody(string message) - { - this.Message = message; - } - - public string Message { get; } - - public string ToJsonFormat() => "{" + $"\"{nameof(MessageBody)}\" :" + "{" + $"\"{nameof(this.Message)}\"" + " :\"" + this.Message + "\"}" +"}"; - } -} diff --git a/examples/UniNetty.Examples.HttpServer/UniNetty.Examples.HttpServer.csproj b/examples/UniNetty.Examples.HttpServer/UniNetty.Examples.HttpServer.csproj deleted file mode 100644 index a0eab0c..0000000 --- a/examples/UniNetty.Examples.HttpServer/UniNetty.Examples.HttpServer.csproj +++ /dev/null @@ -1,11 +0,0 @@ - - - netstandard2.1;net6.0;net8.0 - false - true - - - - - - \ No newline at end of file diff --git a/examples/UniNetty.Examples.QuoteOfTheMoment.Client/QuoteOfTheMomentClient.cs b/examples/UniNetty.Examples.QuoteOfTheMoment.Client/QuoteOfTheMomentClient.cs deleted file mode 100644 index 5fe0a68..0000000 --- a/examples/UniNetty.Examples.QuoteOfTheMoment.Client/QuoteOfTheMomentClient.cs +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Net; -using System.Text; -using System.Threading.Tasks; -using UniNetty.Buffers; -using UniNetty.Common.Internal.Logging; -using UniNetty.Transport.Bootstrapping; -using UniNetty.Transport.Channels; -using UniNetty.Transport.Channels.Sockets; - -namespace UniNetty.Examples.QuoteOfTheMoment.Client -{ - public class QuoteOfTheMomentClient - { - private static readonly IInternalLogger Logger = InternalLoggerFactory.GetInstance(); - private MultithreadEventLoopGroup _group; - - public async Task StartAsync(int port) - { - _group = new MultithreadEventLoopGroup(); - - var bootstrap = new Bootstrap(); - bootstrap - .Group(_group) - .Channel() - .Option(ChannelOption.SoBroadcast, true) - .Handler(new ActionChannelInitializer(channel => - { - channel.Pipeline.AddLast("Quote", new QuoteOfTheMomentClientHandler()); - })); - - IChannel clientChannel = await bootstrap.BindAsync(IPEndPoint.MinPort); - - Logger.Info("Sending broadcast QOTM"); - - // Broadcast the QOTM request to port. - byte[] bytes = Encoding.UTF8.GetBytes("QOTM?"); - IByteBuffer buffer = Unpooled.WrappedBuffer(bytes); - await clientChannel.WriteAndFlushAsync( - new DatagramPacket( - buffer, - new IPEndPoint(IPAddress.Broadcast, port))); - - Logger.Info("Waiting for response."); - - await Task.Delay(5000); - Logger.Info("Waiting for response time 5000 completed. Closing client channel."); - - await clientChannel.CloseAsync(); - } - - public async Task StopAsync() - { - await _group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)); - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.QuoteOfTheMoment.Client/QuoteOfTheMomentClientHandler.cs b/examples/UniNetty.Examples.QuoteOfTheMoment.Client/QuoteOfTheMomentClientHandler.cs deleted file mode 100644 index ab930fa..0000000 --- a/examples/UniNetty.Examples.QuoteOfTheMoment.Client/QuoteOfTheMomentClientHandler.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using UniNetty.Common.Internal.Logging; - -namespace UniNetty.Examples.QuoteOfTheMoment.Client -{ - using System; - using System.Text; - using UniNetty.Transport.Channels; - using UniNetty.Transport.Channels.Sockets; - - public class QuoteOfTheMomentClientHandler : SimpleChannelInboundHandler - { - private static readonly IInternalLogger Logger = InternalLoggerFactory.GetInstance(); - - protected override void ChannelRead0(IChannelHandlerContext ctx, DatagramPacket packet) - { - Logger.Info($"Client Received => {packet}"); - - if (!packet.Content.IsReadable()) - { - return; - } - - string message = packet.Content.ToString(Encoding.UTF8); - if (!message.StartsWith("QOTM: ")) - { - return; - } - - Logger.Info($"Quote of the Moment: {message.Substring(6)}"); - ctx.CloseAsync(); - } - - public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) - { - Logger.Info("Exception: " + exception); - context.CloseAsync(); - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.QuoteOfTheMoment.Client/UniNetty.Examples.QuoteOfTheMoment.Client.csproj b/examples/UniNetty.Examples.QuoteOfTheMoment.Client/UniNetty.Examples.QuoteOfTheMoment.Client.csproj deleted file mode 100644 index 56baf2e..0000000 --- a/examples/UniNetty.Examples.QuoteOfTheMoment.Client/UniNetty.Examples.QuoteOfTheMoment.Client.csproj +++ /dev/null @@ -1,10 +0,0 @@ - - - netstandard2.1;net6.0;net8.0 - false - - - - - - \ No newline at end of file diff --git a/examples/UniNetty.Examples.QuoteOfTheMoment.Server/QuoteOfTheMomentServer.cs b/examples/UniNetty.Examples.QuoteOfTheMoment.Server/QuoteOfTheMomentServer.cs deleted file mode 100644 index 11142d3..0000000 --- a/examples/UniNetty.Examples.QuoteOfTheMoment.Server/QuoteOfTheMomentServer.cs +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Threading.Tasks; -using UniNetty.Common.Internal.Logging; -using UniNetty.Handlers.Logging; -using UniNetty.Transport.Bootstrapping; -using UniNetty.Transport.Channels; -using UniNetty.Transport.Channels.Sockets; - -namespace UniNetty.Examples.QuoteOfTheMoment.Server -{ - public class QuoteOfTheMomentServer - { - private static readonly IInternalLogger Logger = InternalLoggerFactory.GetInstance(); - - private MultithreadEventLoopGroup _group; - private IChannel _channel; - - public async Task StartAsync(int port) - { - _group = new MultithreadEventLoopGroup(); - var bootstrap = new Bootstrap(); - bootstrap - .Group(_group) - .Channel() - .Option(ChannelOption.SoBroadcast, true) - .Handler(new LoggingHandler("SRV-LSTN")) - .Handler(new ActionChannelInitializer(channel => - { - channel.Pipeline.AddLast("Quote", new QuoteOfTheMomentServerHandler()); - })); - - _channel = await bootstrap.BindAsync(port); - //Logger.Info("Press any key to terminate the server."); - } - - public async Task StopAsync() - { - await _channel.CloseAsync(); - await _group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)); - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.QuoteOfTheMoment.Server/QuoteOfTheMomentServerHandler.cs b/examples/UniNetty.Examples.QuoteOfTheMoment.Server/QuoteOfTheMomentServerHandler.cs deleted file mode 100644 index 92db1f8..0000000 --- a/examples/UniNetty.Examples.QuoteOfTheMoment.Server/QuoteOfTheMomentServerHandler.cs +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using UniNetty.Common.Internal.Logging; - -namespace UniNetty.Examples.QuoteOfTheMoment.Server -{ - using System; - using System.Text; - using UniNetty.Buffers; - using UniNetty.Transport.Channels; - using UniNetty.Transport.Channels.Sockets; - - public class QuoteOfTheMomentServerHandler : SimpleChannelInboundHandler - { - private static readonly IInternalLogger Logger = InternalLoggerFactory.GetInstance(); - - static readonly Random Random = new Random(); - - // Quotes from Mohandas K. Gandhi: - static readonly string[] Quotes = - { - "Where there is love there is life.", - "First they ignore you, then they laugh at you, then they fight you, then you win.", - "Be the change you want to see in the world.", - "The weak can never forgive. Forgiveness is the attribute of the strong.", - }; - - static string NextQuote() - { - int quoteId = Random.Next(Quotes.Length); - return Quotes[quoteId]; - } - - protected override void ChannelRead0(IChannelHandlerContext ctx, DatagramPacket packet) - { - Logger.Info($"Server Received => {packet}"); - - if (!packet.Content.IsReadable()) - { - return; - } - - string message = packet.Content.ToString(Encoding.UTF8); - if (message != "QOTM?") - { - return; - } - - byte[] bytes = Encoding.UTF8.GetBytes("QOTM: " + NextQuote()); - IByteBuffer buffer = Unpooled.WrappedBuffer(bytes); - ctx.WriteAsync(new DatagramPacket(buffer, packet.Sender)); - } - - public override void ChannelReadComplete(IChannelHandlerContext context) => context.Flush(); - - public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) - { - Logger.Info("Exception: " + exception); - context.CloseAsync(); - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.QuoteOfTheMoment.Server/UniNetty.Examples.QuoteOfTheMoment.Server.csproj b/examples/UniNetty.Examples.QuoteOfTheMoment.Server/UniNetty.Examples.QuoteOfTheMoment.Server.csproj deleted file mode 100644 index 52a9063..0000000 --- a/examples/UniNetty.Examples.QuoteOfTheMoment.Server/UniNetty.Examples.QuoteOfTheMoment.Server.csproj +++ /dev/null @@ -1,11 +0,0 @@ - - - netstandard2.1;net6.0;net8.0 - false - - - - - - - \ No newline at end of file diff --git a/examples/UniNetty.Examples.SecureChat.Client/SecureChatClient.cs b/examples/UniNetty.Examples.SecureChat.Client/SecureChatClient.cs deleted file mode 100644 index 6d1a34e..0000000 --- a/examples/UniNetty.Examples.SecureChat.Client/SecureChatClient.cs +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.IO; -using System.Net; -using System.Net.Security; -using System.Security.Cryptography.X509Certificates; -using System.Threading.Tasks; -using UniNetty.Codecs; -using UniNetty.Codecs.Strings; -using UniNetty.Handlers.Tls; -using UniNetty.Transport.Bootstrapping; -using UniNetty.Transport.Channels; -using UniNetty.Transport.Channels.Sockets; - -namespace UniNetty.Examples.SecureChat.Client -{ - public class SecureChatClient - { - private MultithreadEventLoopGroup _group; - private IChannel _channel; - - public async Task StartAsync(X509Certificate2 cert, IPAddress host, int port) - { - _group = new MultithreadEventLoopGroup(); - - var bootstrap = new Bootstrap(); - bootstrap - .Group(_group) - .Channel() - .Option(ChannelOption.TcpNodelay, true) - .Handler(new ActionChannelInitializer(channel => - { - IChannelPipeline pipeline = channel.Pipeline; - - if (cert != null) - { - var targetHost = cert.GetNameInfo(X509NameType.DnsName, false); - pipeline.AddLast(new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost))); - } - - pipeline.AddLast(new DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter())); - pipeline.AddLast(new StringEncoder(), new StringDecoder(), new SecureChatClientHandler()); - })); - - _channel = await bootstrap.ConnectAsync(new IPEndPoint(host, port)); - - for (;;) - { - string line = Console.ReadLine(); - if (string.IsNullOrEmpty(line)) - { - continue; - } - - try - { - await _channel.WriteAndFlushAsync(line + "\r\n"); - } - catch - { - } - - if (string.Equals(line, "bye", StringComparison.OrdinalIgnoreCase)) - { - await _channel.CloseAsync(); - break; - } - } - } - - public async Task StopAsync() - { - await _channel.CloseAsync(); - await _group.ShutdownGracefullyAsync(); - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.SecureChat.Client/SecureChatClientHandler.cs b/examples/UniNetty.Examples.SecureChat.Client/SecureChatClientHandler.cs deleted file mode 100644 index 66365aa..0000000 --- a/examples/UniNetty.Examples.SecureChat.Client/SecureChatClientHandler.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using UniNetty.Common.Internal.Logging; - -namespace UniNetty.Examples.SecureChat.Client -{ - using System; - using UniNetty.Transport.Channels; - - public class SecureChatClientHandler : SimpleChannelInboundHandler - { - private static readonly IInternalLogger Logger = InternalLoggerFactory.GetInstance(); - - protected override void ChannelRead0(IChannelHandlerContext contex, string msg) => Logger.Info(msg); - - public override void ExceptionCaught(IChannelHandlerContext contex, Exception e) - { - Logger.Info($"{DateTime.Now.Millisecond}"); - Logger.Info(e.StackTrace); - contex.CloseAsync(); - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.SecureChat.Client/UniNetty.Examples.SecureChat.Client.csproj b/examples/UniNetty.Examples.SecureChat.Client/UniNetty.Examples.SecureChat.Client.csproj deleted file mode 100644 index 52a9063..0000000 --- a/examples/UniNetty.Examples.SecureChat.Client/UniNetty.Examples.SecureChat.Client.csproj +++ /dev/null @@ -1,11 +0,0 @@ - - - netstandard2.1;net6.0;net8.0 - false - - - - - - - \ No newline at end of file diff --git a/examples/UniNetty.Examples.SecureChat.Server/SecureChatServer.cs b/examples/UniNetty.Examples.SecureChat.Server/SecureChatServer.cs deleted file mode 100644 index 9dbf436..0000000 --- a/examples/UniNetty.Examples.SecureChat.Server/SecureChatServer.cs +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Security.Cryptography.X509Certificates; -using System.Threading.Tasks; -using UniNetty.Codecs; -using UniNetty.Codecs.Strings; -using UniNetty.Handlers.Logging; -using UniNetty.Handlers.Tls; -using UniNetty.Transport.Bootstrapping; -using UniNetty.Transport.Channels; -using UniNetty.Transport.Channels.Sockets; - -namespace UniNetty.Examples.SecureChat.Server -{ - public class SecureChatServer - { - private MultithreadEventLoopGroup _bossGroup; - private MultithreadEventLoopGroup _workerGroup; - - private IChannel _channel; - - public async Task StartAsync(X509Certificate2 cert, int port) - { - _bossGroup = new MultithreadEventLoopGroup(1); - _workerGroup = new MultithreadEventLoopGroup(); - - var STRING_ENCODER = new StringEncoder(); - var STRING_DECODER = new StringDecoder(); - var SERVER_HANDLER = new SecureChatServerHandler(); - - var bootstrap = new ServerBootstrap(); - bootstrap - .Group(_bossGroup, _workerGroup) - .Channel() - .Option(ChannelOption.SoBacklog, 100) - .Handler(new LoggingHandler(LogLevel.INFO)) - .ChildHandler(new ActionChannelInitializer(channel => - { - IChannelPipeline pipeline = channel.Pipeline; - if (cert != null) - { - pipeline.AddLast(TlsHandler.Server(cert)); - } - - pipeline.AddLast(new DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter())); - pipeline.AddLast(STRING_ENCODER, STRING_DECODER, SERVER_HANDLER); - })); - - _channel = await bootstrap.BindAsync(port); - } - - public async Task StopAsync() - { - await _channel.CloseAsync(); - await Task.WhenAll(_bossGroup.ShutdownGracefullyAsync(), _workerGroup.ShutdownGracefullyAsync()); - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.SecureChat.Server/SecureChatServerHandler.cs b/examples/UniNetty.Examples.SecureChat.Server/SecureChatServerHandler.cs deleted file mode 100644 index bea63f4..0000000 --- a/examples/UniNetty.Examples.SecureChat.Server/SecureChatServerHandler.cs +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using UniNetty.Common.Internal.Logging; - -namespace UniNetty.Examples.SecureChat.Server -{ - using System; - using System.Net; - using UniNetty.Transport.Channels; - using UniNetty.Transport.Channels.Groups; - - public class SecureChatServerHandler : SimpleChannelInboundHandler - { - private static readonly IInternalLogger Logger = InternalLoggerFactory.GetInstance(); - - static volatile IChannelGroup group; - - public override void ChannelActive(IChannelHandlerContext contex) - { - IChannelGroup g = group; - if (g == null) - { - lock (this) - { - if (group == null) - { - g = group = new DefaultChannelGroup(contex.Executor); - } - } - } - - contex.WriteAndFlushAsync(string.Format("Welcome to {0} secure chat server!\n", Dns.GetHostName())); - g.Add(contex.Channel); - } - - class EveryOneBut : IChannelMatcher - { - readonly IChannelId id; - - public EveryOneBut(IChannelId id) - { - this.id = id; - } - - public bool Matches(IChannel channel) => channel.Id != this.id; - } - - protected override void ChannelRead0(IChannelHandlerContext contex, string msg) - { - //send message to all but this one - string broadcast = string.Format("[{0}] {1}\n", contex.Channel.RemoteAddress, msg); - string response = string.Format("[you] {0}\n", msg); - group.WriteAndFlushAsync(broadcast, new EveryOneBut(contex.Channel.Id)); - contex.WriteAndFlushAsync(response); - - if (string.Equals("bye", msg, StringComparison.OrdinalIgnoreCase)) - { - contex.CloseAsync(); - } - } - - public override void ChannelReadComplete(IChannelHandlerContext ctx) => ctx.Flush(); - - public override void ExceptionCaught(IChannelHandlerContext ctx, Exception e) - { - Logger.Info("{0}", e.StackTrace); - ctx.CloseAsync(); - } - - public override bool IsSharable => true; - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.SecureChat.Server/UniNetty.Examples.SecureChat.Server.csproj b/examples/UniNetty.Examples.SecureChat.Server/UniNetty.Examples.SecureChat.Server.csproj deleted file mode 100644 index 52a9063..0000000 --- a/examples/UniNetty.Examples.SecureChat.Server/UniNetty.Examples.SecureChat.Server.csproj +++ /dev/null @@ -1,11 +0,0 @@ - - - netstandard2.1;net6.0;net8.0 - false - - - - - - - \ No newline at end of file diff --git a/examples/UniNetty.Examples.Telnet.Client/TelnetClient.cs b/examples/UniNetty.Examples.Telnet.Client/TelnetClient.cs deleted file mode 100644 index deb770f..0000000 --- a/examples/UniNetty.Examples.Telnet.Client/TelnetClient.cs +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Net; -using System.Net.Security; -using System.Security.Cryptography.X509Certificates; -using System.Threading.Tasks; -using UniNetty.Codecs; -using UniNetty.Codecs.Strings; -using UniNetty.Handlers.Tls; -using UniNetty.Transport.Bootstrapping; -using UniNetty.Transport.Channels; -using UniNetty.Transport.Channels.Sockets; - -namespace UniNetty.Examples.Telnet.Client -{ - public class TelnetClient - { - private MultithreadEventLoopGroup _group; - private IChannel _channel; - - public async Task StartAsync(X509Certificate2 cert, IPAddress host, int port) - { - _group = new MultithreadEventLoopGroup(); - - - var bootstrap = new Bootstrap(); - bootstrap - .Group(_group) - .Channel() - .Option(ChannelOption.TcpNodelay, true) - .Handler(new ActionChannelInitializer(channel => - { - IChannelPipeline pipeline = channel.Pipeline; - - if (cert != null) - { - var targetHost = cert.GetNameInfo(X509NameType.DnsName, false); - pipeline.AddLast(new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost))); - } - - pipeline.AddLast(new DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter())); - pipeline.AddLast(new StringEncoder(), new StringDecoder(), new TelnetClientHandler()); - })); - - _channel = await bootstrap.ConnectAsync(new IPEndPoint(host, port)); - - for (;;) - { - string line = Console.ReadLine(); - if (string.IsNullOrEmpty(line)) - { - continue; - } - - try - { - await _channel.WriteAndFlushAsync(line + "\r\n"); - } - catch - { - } - - if (string.Equals(line, "bye", StringComparison.OrdinalIgnoreCase)) - { - await _channel.CloseAsync(); - break; - } - } - } - - public async Task StopAsync() - { - await _channel.CloseAsync(); - await _group.ShutdownGracefullyAsync(); - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.Telnet.Client/TelnetClientHandler.cs b/examples/UniNetty.Examples.Telnet.Client/TelnetClientHandler.cs deleted file mode 100644 index 9ab1ad5..0000000 --- a/examples/UniNetty.Examples.Telnet.Client/TelnetClientHandler.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using UniNetty.Common.Internal.Logging; - -namespace UniNetty.Examples.Telnet.Client -{ - using System; - using UniNetty.Transport.Channels; - - public class TelnetClientHandler : SimpleChannelInboundHandler - { - private static readonly IInternalLogger Logger = InternalLoggerFactory.GetInstance(); - - protected override void ChannelRead0(IChannelHandlerContext contex, string msg) - { - Logger.Info(msg); - } - - public override void ExceptionCaught(IChannelHandlerContext contex, Exception e) - { - Logger.Info($"{DateTime.Now.Millisecond}"); - Logger.Info("{0}", e.StackTrace); - contex.CloseAsync(); - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.Telnet.Client/UniNetty.Examples.Telnet.Client.csproj b/examples/UniNetty.Examples.Telnet.Client/UniNetty.Examples.Telnet.Client.csproj deleted file mode 100644 index 52a9063..0000000 --- a/examples/UniNetty.Examples.Telnet.Client/UniNetty.Examples.Telnet.Client.csproj +++ /dev/null @@ -1,11 +0,0 @@ - - - netstandard2.1;net6.0;net8.0 - false - - - - - - - \ No newline at end of file diff --git a/examples/UniNetty.Examples.Telnet.Server/TelnetServer.cs b/examples/UniNetty.Examples.Telnet.Server/TelnetServer.cs deleted file mode 100644 index c31f611..0000000 --- a/examples/UniNetty.Examples.Telnet.Server/TelnetServer.cs +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Security.Cryptography.X509Certificates; -using System.Threading.Tasks; -using UniNetty.Codecs; -using UniNetty.Codecs.Strings; -using UniNetty.Handlers.Logging; -using UniNetty.Handlers.Tls; -using UniNetty.Transport.Bootstrapping; -using UniNetty.Transport.Channels; -using UniNetty.Transport.Channels.Sockets; - -namespace UniNetty.Examples.Telnet.Server -{ - public class TelnetServer - { - private MultithreadEventLoopGroup _bossGroup; - private MultithreadEventLoopGroup _workerGroup; - private IChannel _channel; - - public async Task StartAsync(X509Certificate2 cert, int port) - { - _bossGroup = new MultithreadEventLoopGroup(1); - _workerGroup = new MultithreadEventLoopGroup(); - - var STRING_ENCODER = new StringEncoder(); - var STRING_DECODER = new StringDecoder(); - var SERVER_HANDLER = new TelnetServerHandler(); - - var bootstrap = new ServerBootstrap(); - bootstrap - .Group(_bossGroup, _workerGroup) - .Channel() - .Option(ChannelOption.SoBacklog, 100) - .Handler(new LoggingHandler(LogLevel.INFO)) - .ChildHandler(new ActionChannelInitializer(channel => - { - IChannelPipeline pipeline = channel.Pipeline; - if (cert != null) - { - pipeline.AddLast(TlsHandler.Server(cert)); - } - - pipeline.AddLast(new DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter())); - pipeline.AddLast(STRING_ENCODER, STRING_DECODER, SERVER_HANDLER); - })); - - _channel = await bootstrap.BindAsync(port); - } - - public async Task StopAsync() - { - await _channel.CloseAsync(); - await Task.WhenAll(_bossGroup.ShutdownGracefullyAsync(), _workerGroup.ShutdownGracefullyAsync()); - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.Telnet.Server/TelnetServerHandler.cs b/examples/UniNetty.Examples.Telnet.Server/TelnetServerHandler.cs deleted file mode 100644 index 6caf007..0000000 --- a/examples/UniNetty.Examples.Telnet.Server/TelnetServerHandler.cs +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using UniNetty.Common.Internal.Logging; - -namespace UniNetty.Examples.Telnet.Server -{ - using System; - using System.Net; - using System.Threading.Tasks; - using UniNetty.Transport.Channels; - - public class TelnetServerHandler : SimpleChannelInboundHandler - { - private static readonly IInternalLogger Logger = InternalLoggerFactory.GetInstance(); - - public override void ChannelActive(IChannelHandlerContext contex) - { - contex.WriteAsync($"Welcome to {Dns.GetHostName()} !\r\n"); - contex.WriteAndFlushAsync($"It is {DateTime.Now} now !\r\n"); - } - - protected override void ChannelRead0(IChannelHandlerContext contex, string msg) - { - // Generate and write a response. - string response; - bool close = false; - if (string.IsNullOrEmpty(msg)) - { - response = "Please type something.\r\n"; - } - else if (string.Equals("bye", msg, StringComparison.OrdinalIgnoreCase)) - { - response = "Have a good day!\r\n"; - close = true; - } - else - { - response = "Did you say '" + msg + "'?\r\n"; - } - - Task wait_close = contex.WriteAndFlushAsync(response); - if (close) - { - Task.WaitAll(wait_close); - contex.CloseAsync(); - } - } - - public override void ChannelReadComplete(IChannelHandlerContext contex) - { - contex.Flush(); - } - - public override void ExceptionCaught(IChannelHandlerContext contex, Exception e) - { - Logger.Info("{0}", e.StackTrace); - contex.CloseAsync(); - } - - public override bool IsSharable => true; - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.Telnet.Server/UniNetty.Examples.Telnet.Server.csproj b/examples/UniNetty.Examples.Telnet.Server/UniNetty.Examples.Telnet.Server.csproj deleted file mode 100644 index 52a9063..0000000 --- a/examples/UniNetty.Examples.Telnet.Server/UniNetty.Examples.Telnet.Server.csproj +++ /dev/null @@ -1,11 +0,0 @@ - - - netstandard2.1;net6.0;net8.0 - false - - - - - - - \ No newline at end of file diff --git a/examples/UniNetty.Examples.WebSockets.Client/UniNetty.Examples.WebSockets.Client.csproj b/examples/UniNetty.Examples.WebSockets.Client/UniNetty.Examples.WebSockets.Client.csproj deleted file mode 100644 index 546c514..0000000 --- a/examples/UniNetty.Examples.WebSockets.Client/UniNetty.Examples.WebSockets.Client.csproj +++ /dev/null @@ -1,13 +0,0 @@ - - - - netstandard2.1;net6.0;net8.0 - false - - - - - - - - diff --git a/examples/UniNetty.Examples.WebSockets.Client/WebSocketClient.cs b/examples/UniNetty.Examples.WebSockets.Client/WebSocketClient.cs deleted file mode 100644 index c5f5338..0000000 --- a/examples/UniNetty.Examples.WebSockets.Client/WebSocketClient.cs +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Net; -using System.Net.Security; -using System.Security.Cryptography.X509Certificates; -using System.Threading.Tasks; -using UniNetty.Buffers; -using UniNetty.Codecs.Http; -using UniNetty.Codecs.Http.WebSockets; -using UniNetty.Codecs.Http.WebSockets.Extensions.Compression; -using UniNetty.Common.Internal.Logging; -using UniNetty.Handlers.Tls; -using UniNetty.Transport.Bootstrapping; -using UniNetty.Transport.Channels; -using UniNetty.Transport.Channels.Sockets; - -namespace UniNetty.Examples.WebSockets.Client -{ - public class WebSocketClient - { - private static readonly IInternalLogger Logger = InternalLoggerFactory.GetInstance(); - - private MultithreadEventLoopGroup _group; - private IChannel _channel; - - public async Task StartAsync(X509Certificate2 cert, IPAddress host, int port, string path) - { - var builder = new UriBuilder - { - Scheme = null != cert ? "wss" : "ws", - Host = host.ToString(), - Port = port - }; - - if (!string.IsNullOrEmpty(path)) - { - builder.Path = path; - } - - Uri uri = builder.Uri; - - Logger.Info("Transport type : Socket"); - - _group = new MultithreadEventLoopGroup(); - - var bootstrap = new Bootstrap(); - bootstrap - .Group(_group) - .Option(ChannelOption.TcpNodelay, true) - .Channel(); - - // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00. - // If you change it to V00, ping is not supported and remember to change - // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline. - var handler = new WebSocketClientHandler( - WebSocketClientHandshakerFactory.NewHandshaker( - uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders())); - - bootstrap.Handler(new ActionChannelInitializer(channel => - { - IChannelPipeline pipeline = channel.Pipeline; - if (cert != null) - { - var targetHost = cert.GetNameInfo(X509NameType.DnsName, false); - pipeline.AddLast("tls", new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost))); - } - - pipeline.AddLast( - new HttpClientCodec(), - new HttpObjectAggregator(8192), - WebSocketClientCompressionHandler.Instance, - handler); - })); - - _channel = await bootstrap.ConnectAsync(new IPEndPoint(host, port)); - await handler.HandshakeCompletion; - - Logger.Info("WebSocket handshake completed.\n"); - Logger.Info("\t[bye]:Quit \n\t [ping]:Send ping frame\n\t Enter any text and Enter: Send text frame"); - while (true) - { - string msg = Console.ReadLine(); - if (msg == null) - { - break; - } - else if ("bye".Equals(msg.ToLower())) - { - await _channel.WriteAndFlushAsync(new CloseWebSocketFrame()); - break; - } - else if ("ping".Equals(msg.ToLower())) - { - var frame = new PingWebSocketFrame(Unpooled.WrappedBuffer(new byte[] { 8, 1, 8, 1 })); - await _channel.WriteAndFlushAsync(frame); - } - else - { - WebSocketFrame frame = new TextWebSocketFrame(msg); - await _channel.WriteAndFlushAsync(frame); - } - } - } - - public async Task StopAsync() - { - await _channel.CloseAsync(); - await _group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)); - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.WebSockets.Client/WebSocketClientHandler.cs b/examples/UniNetty.Examples.WebSockets.Client/WebSocketClientHandler.cs deleted file mode 100644 index e058566..0000000 --- a/examples/UniNetty.Examples.WebSockets.Client/WebSocketClientHandler.cs +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using UniNetty.Common.Internal.Logging; - -namespace UniNetty.Examples.WebSockets.Client -{ - using System; - using System.Text; - using System.Threading.Tasks; - using UniNetty.Codecs.Http; - using UniNetty.Codecs.Http.WebSockets; - using UniNetty.Common.Concurrency; - using UniNetty.Common.Utilities; - using UniNetty.Transport.Channels; - using TaskCompletionSource = UniNetty.Common.Concurrency.TaskCompletionSource; - - public class WebSocketClientHandler : SimpleChannelInboundHandler - { - private static readonly IInternalLogger Logger = InternalLoggerFactory.GetInstance(); - - readonly WebSocketClientHandshaker handshaker; - readonly TaskCompletionSource completionSource; - - public WebSocketClientHandler(WebSocketClientHandshaker handshaker) - { - this.handshaker = handshaker; - this.completionSource = new TaskCompletionSource(); - } - - public Task HandshakeCompletion => this.completionSource.Task; - - public override void ChannelActive(IChannelHandlerContext ctx) => - this.handshaker.HandshakeAsync(ctx.Channel).LinkOutcome(this.completionSource); - - public override void ChannelInactive(IChannelHandlerContext context) - { - Logger.Info("WebSocket Client disconnected!"); - } - - protected override void ChannelRead0(IChannelHandlerContext ctx, object msg) - { - IChannel ch = ctx.Channel; - if (!this.handshaker.IsHandshakeComplete) - { - try - { - this.handshaker.FinishHandshake(ch, (IFullHttpResponse)msg); - Logger.Info("WebSocket Client connected!"); - this.completionSource.TryComplete(); - } - catch (WebSocketHandshakeException e) - { - Logger.Info("WebSocket Client failed to connect"); - this.completionSource.TrySetException(e); - } - - return; - } - - - if (msg is IFullHttpResponse response) - { - throw new InvalidOperationException( - $"Unexpected FullHttpResponse (getStatus={response.Status}, content={response.Content.ToString(Encoding.UTF8)})"); - } - - if (msg is TextWebSocketFrame textFrame) - { - Logger.Info($"WebSocket Client received message: {textFrame.Text()}"); - } - else if (msg is PongWebSocketFrame) - { - Logger.Info("WebSocket Client received pong"); - } - else if (msg is CloseWebSocketFrame) - { - Logger.Info("WebSocket Client received closing"); - ch.CloseAsync(); - } - } - - public override void ExceptionCaught(IChannelHandlerContext ctx, Exception exception) - { - Logger.Info("Exception: " + exception); - this.completionSource.TrySetException(exception); - ctx.CloseAsync(); - } - } -} diff --git a/examples/UniNetty.Examples.WebSockets.Server/UniNetty.Examples.WebSockets.Server.csproj b/examples/UniNetty.Examples.WebSockets.Server/UniNetty.Examples.WebSockets.Server.csproj deleted file mode 100644 index b99e48e..0000000 --- a/examples/UniNetty.Examples.WebSockets.Server/UniNetty.Examples.WebSockets.Server.csproj +++ /dev/null @@ -1,11 +0,0 @@ - - - netstandard2.1;net6.0;net8.0 - false - true - - - - - - diff --git a/examples/UniNetty.Examples.WebSockets.Server/WebSocketServer.cs b/examples/UniNetty.Examples.WebSockets.Server/WebSocketServer.cs deleted file mode 100644 index cd7b332..0000000 --- a/examples/UniNetty.Examples.WebSockets.Server/WebSocketServer.cs +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Net; -using System.Security.Cryptography.X509Certificates; -using System.Threading.Tasks; -using UniNetty.Codecs.Http; -using UniNetty.Common.Internal.Logging; -using UniNetty.Handlers.Tls; -using UniNetty.Transport.Bootstrapping; -using UniNetty.Transport.Channels; -using UniNetty.Transport.Channels.Sockets; - -namespace UniNetty.Examples.WebSockets.Server -{ - public class WebSocketServer - { - private static readonly IInternalLogger Logger = InternalLoggerFactory.GetInstance(); - - private MultithreadEventLoopGroup _bossGroup; - private MultithreadEventLoopGroup _workGroup; - private IChannel _channel; - - public async Task StartAsync(X509Certificate2 cert, int port) - { - _bossGroup = new MultithreadEventLoopGroup(1); - _workGroup = new MultithreadEventLoopGroup(); - - var bootstrap = new ServerBootstrap(); - bootstrap.Group(_bossGroup, _workGroup); - bootstrap.Channel(); - - bootstrap - .Option(ChannelOption.SoBacklog, 8192) - .ChildHandler(new ActionChannelInitializer(channel => - { - IChannelPipeline pipeline = channel.Pipeline; - if (cert != null) - { - pipeline.AddLast(TlsHandler.Server(cert)); - } - - pipeline.AddLast(new HttpServerCodec()); - pipeline.AddLast(new HttpObjectAggregator(65536)); - pipeline.AddLast(new WebSocketServerHandler(null != cert)); - })); - - _channel = await bootstrap.BindAsync(port); - - Logger.Info("Open your web browser and navigate to " - + $"{(null != cert ? "https" : "http")}" - + $"://127.0.0.1:{port}/"); - Logger.Info("Listening on " - + $"{(null != cert ? "wss" : "ws")}" - + $"://127.0.0.1:{port}/websocket"); - } - - public async Task StopAsync() - { - await _channel.CloseAsync(); - await _workGroup.ShutdownGracefullyAsync(); - await _bossGroup.ShutdownGracefullyAsync(); - } - } -} \ No newline at end of file diff --git a/examples/UniNetty.Examples.WebSockets.Server/WebSocketServerBenchmarkPage.cs b/examples/UniNetty.Examples.WebSockets.Server/WebSocketServerBenchmarkPage.cs deleted file mode 100644 index bd4391f..0000000 --- a/examples/UniNetty.Examples.WebSockets.Server/WebSocketServerBenchmarkPage.cs +++ /dev/null @@ -1,173 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -namespace UniNetty.Examples.WebSockets.Server -{ - using System.Text; - using UniNetty.Buffers; - - static class WebSocketServerBenchmarkPage - { - const string Newline = "\r\n"; - - public static IByteBuffer GetContent(string webSocketLocation) => - Unpooled.WrappedBuffer( - Encoding.ASCII.GetBytes( - "Web Socket Performance Test" + Newline + - "" + Newline + - "

WebSocket Performance Test

" + Newline + - "" + Newline + - "
" + Newline + - - "
" + Newline + - "Message size:" + - "
" + Newline + - "Number of messages:" + - "
" + Newline + - "Data Type:" + - "text" + - "binary
" + Newline + - "Mode:
" + Newline + - "" + - "Wait for response after each messages
" + Newline + - "" + - "Send all messages and then wait for all responses
" + Newline + - "Verify responded messages
" + Newline + - "" + Newline + - "

Output

" + Newline + - "" + Newline + - "
" + Newline + - "" + Newline + - "
" + Newline + - - "" + Newline + - "" + Newline + - "" + Newline)); - } -} diff --git a/examples/UniNetty.Examples.WebSockets.Server/WebSocketServerHandler.cs b/examples/UniNetty.Examples.WebSockets.Server/WebSocketServerHandler.cs deleted file mode 100644 index f252bcc..0000000 --- a/examples/UniNetty.Examples.WebSockets.Server/WebSocketServerHandler.cs +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Copyright (c) Ikpil Choi ikpil@naver.com All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using UniNetty.Common.Internal.Logging; - -namespace UniNetty.Examples.WebSockets.Server -{ - using System; - using System.Diagnostics; - using System.Text; - using System.Threading.Tasks; - using UniNetty.Buffers; - using UniNetty.Codecs.Http; - using UniNetty.Codecs.Http.WebSockets; - using UniNetty.Common.Utilities; - using UniNetty.Transport.Channels; - - using static UniNetty.Codecs.Http.HttpVersion; - using static UniNetty.Codecs.Http.HttpResponseStatus; - - public sealed class WebSocketServerHandler : SimpleChannelInboundHandler - { - private static readonly IInternalLogger Logger = InternalLoggerFactory.GetInstance(); - - const string WebsocketPath = "/websocket"; - - private bool _ssl; - WebSocketServerHandshaker handshaker; - - public WebSocketServerHandler(bool ssl) - { - _ssl = ssl; - } - - protected override void ChannelRead0(IChannelHandlerContext ctx, object msg) - { - if (msg is IFullHttpRequest request) - { - this.HandleHttpRequest(ctx, request); - } - else if (msg is WebSocketFrame frame) - { - this.HandleWebSocketFrame(ctx, frame); - } - } - - public override void ChannelReadComplete(IChannelHandlerContext context) => context.Flush(); - - void HandleHttpRequest(IChannelHandlerContext ctx, IFullHttpRequest req) - { - // Handle a bad request. - if (!req.Result.IsSuccess) - { - SendHttpResponse(ctx, req, new DefaultFullHttpResponse(Http11, BadRequest)); - return; - } - - // Allow only GET methods. - if (!Equals(req.Method, HttpMethod.Get)) - { - SendHttpResponse(ctx, req, new DefaultFullHttpResponse(Http11, Forbidden)); - return; - } - - // Send the demo page and favicon.ico - if ("/".Equals(req.Uri)) - { - IByteBuffer content = WebSocketServerBenchmarkPage.GetContent(GetWebSocketLocation(req)); - var res = new DefaultFullHttpResponse(Http11, OK, content); - - res.Headers.Set(HttpHeaderNames.ContentType, "text/html; charset=UTF-8"); - HttpUtil.SetContentLength(res, content.ReadableBytes); - - SendHttpResponse(ctx, req, res); - return; - } - if ("/favicon.ico".Equals(req.Uri)) - { - var res = new DefaultFullHttpResponse(Http11, NotFound); - SendHttpResponse(ctx, req, res); - return; - } - - // Handshake - var wsFactory = new WebSocketServerHandshakerFactory( - GetWebSocketLocation(req), null, true, 5 * 1024 * 1024); - this.handshaker = wsFactory.NewHandshaker(req); - if (this.handshaker == null) - { - WebSocketServerHandshakerFactory.SendUnsupportedVersionResponse(ctx.Channel); - } - else - { - this.handshaker.HandshakeAsync(ctx.Channel, req); - } - } - - void HandleWebSocketFrame(IChannelHandlerContext ctx, WebSocketFrame frame) - { - // Check for closing frame - if (frame is CloseWebSocketFrame) - { - this.handshaker.CloseAsync(ctx.Channel, (CloseWebSocketFrame)frame.Retain()); - return; - } - - if (frame is PingWebSocketFrame) - { - ctx.WriteAsync(new PongWebSocketFrame((IByteBuffer)frame.Content.Retain())); - return; - } - - if (frame is TextWebSocketFrame) - { - // Echo the frame - ctx.WriteAsync(frame.Retain()); - return; - } - - if (frame is BinaryWebSocketFrame) - { - // Echo the frame - ctx.WriteAsync(frame.Retain()); - } - } - - static void SendHttpResponse(IChannelHandlerContext ctx, IFullHttpRequest req, IFullHttpResponse res) - { - // Generate an error page if response getStatus code is not OK (200). - if (res.Status.Code != 200) - { - IByteBuffer buf = Unpooled.CopiedBuffer(Encoding.UTF8.GetBytes(res.Status.ToString())); - res.Content.WriteBytes(buf); - buf.Release(); - HttpUtil.SetContentLength(res, res.Content.ReadableBytes); - } - - // Send the response and close the connection if necessary. - Task task = ctx.Channel.WriteAndFlushAsync(res); - if (!HttpUtil.IsKeepAlive(req) || res.Status.Code != 200) - { - task.ContinueWith((t, c) => ((IChannelHandlerContext)c).CloseAsync(), - ctx, TaskContinuationOptions.ExecuteSynchronously); - } - } - - public override void ExceptionCaught(IChannelHandlerContext ctx, Exception e) - { - Logger.Info($"{nameof(WebSocketServerHandler)} {0}", e); - ctx.CloseAsync(); - } - - private string GetWebSocketLocation(IFullHttpRequest req) - { - bool result = req.Headers.TryGet(HttpHeaderNames.Host, out ICharSequence value); - Debug.Assert(result, "Host header does not exist."); - string location= value.ToString() + WebsocketPath; - - if (_ssl) - { - return "wss://" + location; - } - else - { - return "ws://" + location; - } - } - } -}