高性能 DotNetty Server Clinet Demo .NetCore

Nuget 引用

client 端

Install-Package DotNetty.Codecs  -Version 0.6.0
Install-Package DotNetty.Handlers -Version 0.6.0
Install-Package DotNetty.Transport -Version 0.6.0

Server端

Install-Package DotNetty.Codecs  -Version 0.6.0
Install-Package DotNetty.Transport -Version 0.6.0

服务端代码

        static void Main(string[] args)
        {
            Server server = new Server();
            server.Listen(9999).Wait();
            Console.WriteLine("服务启动");
            Console.ReadLine();
        }
    /// 
    /// 服务
    /// 
    public class Server
    {
        public async Task Listen(int port)
        {
            var boos = new MultithreadEventLoopGroup(1);
            var work = new MultithreadEventLoopGroup();

            var bootstrap = new ServerBootstrap();
            bootstrap.Group(boos, work)
                .Channel()
                .Option(ChannelOption.SoBacklog, 100)
                .ChildHandler(new ActionChannelInitializer(channel=> {
                    IChannelPipeline pipeline = channel.Pipeline;

                    pipeline.AddLast(new ServerMessageHandler());
                }));
            IChannel boundChannel = await bootstrap.BindAsync(port);
        }
    }
    public class ServerMessageHandler : ChannelHandlerAdapter
    {
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            var buffer = message as IByteBuffer;
            if (buffer != null)
            {
                string receiveData = buffer.ToString(Encoding.UTF8);
                Console.WriteLine("服务端获取到:" + receiveData);
                byte[] messageBytes = Encoding.UTF8.GetBytes(receiveData);
                IByteBuffer byteBuffer = Unpooled.Buffer(256);
                byteBuffer.WriteBytes(messageBytes);
                context.WriteAndFlushAsync(byteBuffer);
            }
        }
        public override void ChannelReadComplete(IChannelHandlerContext context) => context.Flush();

        public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
        {
            context.CloseAsync();
        }
    }

客户端代码

        static void Main(string[] args)
        {
            Clinet clinet = new Clinet();
            clinet.Connect("127.0.0.1", 9999);
            Console.WriteLine("客户端开始连接!");
            string content = "";
            while (!(content = Console.ReadLine()).Contains("Exit", StringComparison.InvariantCultureIgnoreCase))
            {
                clinet.SendMessage(content);
            }
            Console.ReadLine();
        }
    /// 
    /// 客户端
    /// 
    public class Clinet
    {
        public static IChannel Channel { set; get; }
        public static IEventLoopGroup Group { set; get; }
        public static ClientMessageHandler clientMessageHandler = new ClientMessageHandler();
        public async void Connect(string 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;
                    pipeline.AddLast(clientMessageHandler);
                }));
            Channel = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse(host), port));
        }
        public async void Close()
        {
            await Channel.CloseAsync();
            await Group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
        }
        /// 
        /// 发送消息
        /// 
        /// 
        public bool SendMessage(string message)
        {
            if (message == null)
            {
                return false;
            }
            IByteBuffer buffer = Unpooled.Buffer(256);

            byte[] messageBytes = Encoding.UTF8.GetBytes(message);
            buffer.WriteBytes(messageBytes);
            Channel.WriteAndFlushAsync(buffer);

            return true;
        }
    }
    public class ClientMessageHandler : ChannelHandlerAdapter
    {
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            var byteBuffer = message as IByteBuffer;

            if (byteBuffer != null)
            {
                var data = byteBuffer.ToString(Encoding.UTF8);
                Console.WriteLine("客户端收到:" + data);
            }
        }

        public override void ChannelReadComplete(IChannelHandlerContext context) => context.Flush();

        public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
        {
            Console.WriteLine("Exception: " + exception);
            context.CloseAsync();
        }
    }

最后的效果

高性能 DotNetty Server Clinet Demo .NetCore_第1张图片

效果不错,第一次学习,就搞出来了。加油。

你可能感兴趣的:(.NetCore)