總覽鏈接:
https://blog.csdn.net/a1234012340a/article/details/91040073
客戶端代碼:
static async Task RunClientAsync()
{
var group = new MultithreadEventLoopGroup();
try
{
var bootstrap = new Bootstrap();
bootstrap
.Group(group)
.Channel<TcpSocketChannel>()
.Option(ChannelOption.TcpNodelay, true)
.Handler(
new ActionChannelInitializer<ISocketChannel>(
channel =>
{
IChannelPipeline pipeline = channel.Pipeline;
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(new IdleStateHandler(5, 0, 0));
pipeline.AddLast("echo", new EchoClientHandler());
}));
IPAddress ip = IPAddress.Parse("127.0.0.1");
IChannel clientChannel = await bootstrap.ConnectAsync(new IPEndPoint(ip, 8007));
// 建立死循環,類同於While(true)
for (; ; ) // (4)
{
Console.WriteLine("input you data:");
// 根據設置建立緩存區大小
IByteBuffer initialMessage = Unpooled.Buffer(256); // (1)
string r = Console.ReadLine();
// 將數據流寫入緩衝區
initialMessage.WriteBytes(Encoding.UTF8.GetBytes(r ?? throw new InvalidOperationException())); // (2)
// 將緩衝區數據流寫入到管道中
await clientChannel.WriteAndFlushAsync(initialMessage); // (3)
if (r.Contains("bye"))
break;
}
Console.WriteLine("byebye");
await clientChannel.CloseAsync();
}
finally
{
await group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
}
}
static void Main() => RunClientAsync().Wait();
客戶端Handler代碼:
readonly IByteBuffer initialMessage;
public override void ChannelActive(IChannelHandlerContext context) => context.WriteAndFlushAsync(this.initialMessage);
public override void ChannelRead(IChannelHandlerContext context, object message)
{
#region 無操作
//什麼也不想做
#endregion
}
public override void ChannelReadComplete(IChannelHandlerContext context) => context.Flush();
public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
{
Console.WriteLine("Exception: " + exception);
context.CloseAsync();
}
至此客戶端打完收工
完全個人研究,有錯希望大神糾正。也可留下您的聯繫方式,共同探討
作者:Henny_CHN
轉載請標明出處,原文地址:
https://blog.csdn.net/a1234012340a/article/details/93138687
如果感覺本文對您有幫助,請留下您的贊,您的支持是我堅持寫作最大的動力,謝謝!