mirror of
https://github.com/Azure/DotNetty.git
synced 2026-10-19 06:31:20 +08:00
4dab326ce1
Motivation: DotNetty is already working under .NET Core and full .NET Framework but support for other platforms (like UWP) is missing. It is important to have reach in that space as well. Modifications: - Thread-based functionality is modeled with Tasks (as threads are not part of supported .NET Standard 1.3). - IPlatform / DefaultPlatform are added to abstract platform-dependent functionality not available across the board. - UWP platform implementation is demonstrated in an example along StreamSocket-based Channel. Result: UWP support for DotNetty is easy to implement now. Basics for platform-dependent code are added making further development easier.
54 lines
1.9 KiB
C#
54 lines
1.9 KiB
C#
// Copyright (c) Microsoft. All rights reserved.
|
|
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
|
|
namespace UWPEcho.Client
|
|
{
|
|
using System;
|
|
using System.Diagnostics;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using DotNetty.Buffers;
|
|
using DotNetty.Transport.Channels;
|
|
|
|
public class EchoClientHandler : ChannelHandlerAdapter
|
|
{
|
|
readonly IByteBuffer initialMessage;
|
|
readonly Action<object> logger;
|
|
|
|
public EchoClientHandler(Action<object> logger)
|
|
{
|
|
this.logger = logger;
|
|
this.initialMessage = Unpooled.Buffer(256);
|
|
byte[] messageBytes = Encoding.UTF8.GetBytes("Hello from UWP!");
|
|
this.initialMessage.WriteBytes(messageBytes);
|
|
}
|
|
|
|
public override void ChannelActive(IChannelHandlerContext context) => context.WriteAndFlushAsync(this.initialMessage);
|
|
|
|
public override async void ChannelRead(IChannelHandlerContext context, object message)
|
|
{
|
|
try
|
|
{
|
|
var byteBuffer = message as IByteBuffer;
|
|
if (byteBuffer != null)
|
|
{
|
|
string str = byteBuffer.ToString(Encoding.UTF8);
|
|
Debug.WriteLine("Received from server: " + str);
|
|
this.logger(str);
|
|
}
|
|
await context.WriteAsync(message);
|
|
// Throttle the client:
|
|
await Task.Delay(100);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
string str = string.Format("Error reading from channel: {0}", ex.Message);
|
|
this.logger(str);
|
|
}
|
|
}
|
|
|
|
public override void ChannelReadComplete(IChannelHandlerContext context) => context.Flush();
|
|
|
|
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) => context.CloseAsync();
|
|
}
|
|
} |