Skip to content

Commit

Permalink
added uninetty example window
Browse files Browse the repository at this point in the history
  • Loading branch information
ikpil committed Oct 27, 2024
1 parent 7575134 commit 8900a8e
Show file tree
Hide file tree
Showing 47 changed files with 2,283 additions and 14 deletions.
5 changes: 3 additions & 2 deletions Editor/UniNetty.Editor/UniNetty.Editor.asmdef
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "UniNetty.Editor",
"rootNamespace": "UniNetty",
"rootNamespace": "UniNetty.Editor",
"references": [
"UniNetty.Logging",
"UniNetty.Common",
Expand All @@ -10,7 +10,8 @@
"UniNetty.Codecs",
"UniNetty.Codecs.Http",
"UniNetty.Codecs.Mqtt",
"UniNetty.Codecs.Redis"
"UniNetty.Codecs.Redis",
"UniNetty.Examples"
],
"includePlatforms": [],
"excludePlatforms": [],
Expand Down
25 changes: 25 additions & 0 deletions Editor/UniNetty.Editor/UniNettyExampleWindow.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using UniNetty.Examples.Discard.Client;
using UniNetty.Examples.Discard.Server;
using UnityEditor;
using UnityEngine;

namespace UniNetty.Editor
{
public class UniNettyExampleWindow : EditorWindow
{
public void ExampleDiscard()
{
var server = new DiscardServer();
var client = new DiscardClient();
}

// GUI 그리기
private void OnGUI()
{
if (GUILayout.Button("Discard"))
{
ExampleDiscard();
}
}
}
}
8 changes: 5 additions & 3 deletions Editor/UniNetty.Editor/UniNettyMenu.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
using UnityEditor;
using UnityEngine;

namespace UniNetty
namespace UniNetty.Editor
{
public class UniNettyMenu
{
[MenuItem("UniNetty/Examples")]
public static void MyMenuItem()
{
Debug.Log("examples");
var window = EditorWindow.GetWindow<UniNettyExampleWindow>();
window.titleContent = new GUIContent("UniNetty Examples");
window.Show();
}
}
}
}
62 changes: 62 additions & 0 deletions Examples/UniNetty.Examples.Discard.Client/DiscardClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// 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<TcpSocketChannel>()
.Option(ChannelOption.TcpNodelay, true)
.Handler(new ActionChannelInitializer<ISocketChannel>(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();
}
}
}
73 changes: 73 additions & 0 deletions Examples/UniNetty.Examples.Discard.Client/DiscardClientHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// 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<object>
{
private static readonly IInternalLogger Logger = InternalLoggerFactory.GetInstance<DiscardClientHandler>();

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();
}
}
}
}
85 changes: 85 additions & 0 deletions Examples/UniNetty.Examples.Discard.Server/DiscardServer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// 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<DiscardServer>();

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<TcpServerSocketChannel>()
.Option(ChannelOption.SoBacklog, 100)
.Handler(new LoggingHandler("LSTN"))
.ChildHandler(new ActionChannelInitializer<ISocketChannel>(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");
}
}
}
}
27 changes: 27 additions & 0 deletions Examples/UniNetty.Examples.Discard.Server/DiscardServerHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// 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<object>
{
private static readonly IInternalLogger Logger = InternalLoggerFactory.GetInstance<DiscardServerHandler>();

protected override void ChannelRead0(IChannelHandlerContext context, object message)
{
}

public override void ExceptionCaught(IChannelHandlerContext ctx, Exception e)
{
Logger.Info("{0}", e.ToString());
ctx.CloseAsync();
}
}
}
58 changes: 58 additions & 0 deletions Examples/UniNetty.Examples.Echo.Client/EchoClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// 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<TcpSocketChannel>()
.Option(ChannelOption.TcpNodelay, true)
.Handler(new ActionChannelInitializer<ISocketChannel>(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));
}
}
}
Loading

0 comments on commit 8900a8e

Please sign in to comment.