C# using Netty demo

Write the directory title here

  • a server
  • Second client

A server

using System;
using System. Text;
using System. Threading. Tasks;
using DotNetty. Buffers;
using DotNetty. Codecs;
using DotNetty.Common.Concurrency;
using DotNetty. Transport. Bootstrapping;
using DotNetty. Transport. Channels;
using DotNetty.Transport.Channels.Sockets;

namespace Nettyfwq
{<!-- -->
    public class TcpServer
    {<!-- -->
        public async Task Start()
        {<!-- -->
            IEventLoopGroup bossGroup = new MultithreadEventLoopGroup(1);
            IEventLoopGroup workerGroup = new MultithreadEventLoopGroup();

            try
            {<!-- -->
                ServerBootstrap bootstrap = new ServerBootstrap()
                    .Group(bossGroup, workerGroup)
                    .Channel<TcpServerSocketChannel>()
                    .Option(ChannelOption.SoBacklog, 100)
                    .ChildHandler(new ActionChannelInitializer<ISocketChannel>(channel =>
                    {<!-- -->
                        IChannelPipeline pipeline = channel.Pipeline;
                        pipeline.AddLast(new LengthFieldBasedFrameDecoder(1024, 0, 4, 0, 4));
                        pipeline.AddLast(new StringDecoder(Encoding.UTF8));
                        pipeline.AddLast(new LengthFieldPrepender(4));
                        pipeline.AddLast(new StringEncoder(Encoding.UTF8));
                        pipeline.AddLast(new TcpServerHandler());
                    }));

                IChannel boundChannel = await bootstrap. BindAsync(8888);
                Console.WriteLine("TCP server started on port 8888. Press any key to exit.");
                Console. ReadKey();

                await boundChannel. CloseAsync();
            }
            finally
            {<!-- -->
                await Task. WhenAll(
                    bossGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)),
                    workerGroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1))
                );
            }
        }
    }

    public class TcpServerHandler : SimpleChannelInboundHandler<string>
    {<!-- -->
        protected override void ChannelRead0(IChannelHandlerContext context, string message)
        {<!-- -->
            Console.WriteLine($"Received data: {<!-- -->message}");

            // Process the received data here

            context.Channel.WriteAndFlushAsync("I am the server");
        }

        public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
        {<!-- -->
            Console.WriteLine($"Exception: {<!-- -->exception}");
            context. CloseAsync();
        }

        public override void ChannelActive(IChannelHandlerContext context)
        {<!-- -->
            string clientName = context.Channel.RemoteAddress.ToString();

            // print client name
            Console.WriteLine("Connect to a client:" + clientName);

            base. ChannelActive(context);
            Console.WriteLine("Connect to a client:" + clientName);
        }
    }

    public class Program
    {<!-- -->
        public static async Task Main(string[] args)
        {<!-- -->
            TcpServer server = new TcpServer();
            await server. Start();
        }
    }
}

Second client

using System;
using System. Text;
using System. Threading. Tasks;
using DotNetty. Buffers;
using DotNetty. Codecs;
using DotNetty.Common.Concurrency;
using DotNetty. Transport. Bootstrapping;
using DotNetty. Transport. Channels;
using DotNetty.Transport.Channels.Sockets;

namespace Nuttykhd
{<!-- -->
    public class DotNettyClient
    {<!-- -->
        private MultithreadEventLoopGroup group;
        private Bootstrap bootstrap;
        private IChannel channel;

        public async Task StartAsync()
        {<!-- -->
            group = new MultithreadEventLoopGroup();

            try
            {<!-- -->
                bootstrap = new Bootstrap()
                    .Group(group)
                    .Channel<TcpSocketChannel>()
                    .Option(ChannelOption.TcpNodelay, true)
                    .Handler(new ActionChannelInitializer<ISocketChannel>(channel =>
                    {<!-- -->
                        IChannelPipeline pipeline = channel.Pipeline;
                        pipeline.AddLast(new LengthFieldBasedFrameDecoder(1024, 0, 4, 0, 4));
                        pipeline.AddLast(new StringDecoder(Encoding.UTF8));
                        pipeline.AddLast(new LengthFieldPrepender(4));
                        pipeline.AddLast(new StringEncoder(Encoding.UTF8));
                        pipeline.AddLast(new DotNettyClientHandler());
                    }));

                channel = await bootstrap. ConnectAsync("127.0.0.1", 8888);
                string clientName = "Xiao Wang";
                byte[] nameBytes = Encoding.UTF8.GetBytes(clientName);
                await channel.WriteAndFlushAsync(Unpooled.WrappedBuffer(nameBytes));

                Console.WriteLine("Connected to server.");

                // send message to server
                SendMessage("I am the client");

                // Pause for a while to simulate other operations of the client
                await Task. Delay(5000);

                // send more messages to the server
                SendMessage("I send it to Ah Fei");

                 close client connection
                //await channel. CloseAsync();
                //Console.WriteLine("Client connection closed.");
            }
            finally
            {<!-- -->
                await group.ShutdownGracefullyAsync();
            }
        }

        public void SendMessage(string message)
        {<!-- -->
            if (channel != null & amp; & amp; channel. Open)
            {<!-- -->
                channel.WriteAndFlushAsync(message);
                Console.WriteLine("Sent message to server: " + message);
            }
        }
    }

    public class DotNettyClientHandler : SimpleChannelInboundHandler<string>
    {<!-- -->
        protected override void ChannelRead0(IChannelHandlerContext context, string message)
        {<!-- -->
            Console.WriteLine("Received message from server: " + message);
        }
    }

    public class Program
    {<!-- -->
        public static async Task Main()
        {<!-- -->
            DotNettyClient client = new DotNettyClient();
            await client. StartAsync();
        }
    }
}