using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DotNetty.Buffers;
using DotNetty.Handlers.Timeout;
using DotNetty.Transport.Channels;


namespace NotNettyServer
{
    public class ServerHandler : ChannelHandlerAdapter
    {
        public override void ChannelActive(IChannelHandlerContext context)
        {
            base.ChannelActive(context);
            Console.WriteLine("Server ChannelActive");
        }

        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            if (message is IByteBuffer buffer)
            {
                string abc = buffer.ToString(Encoding.UTF8);
               
                Console.WriteLine("收到:" + abc);
            }
            context.WriteAsync(message); //回复
        }

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


        public override void UserEventTriggered(IChannelHandlerContext context, object evt)
        {
            base.UserEventTriggered(context, evt);
            if (evt is IdleStateEvent state)
            {
                if (state == IdleStateEvent.ReaderIdleStateEvent)
                {
                    Console.WriteLine("Read超时");
                }
                else if (state == IdleStateEvent.WriterIdleStateEvent)
                {
                    Console.WriteLine("Write超时");
                }
                if (state == IdleStateEvent.AllIdleStateEvent)
                {
                    Console.WriteLine("All超时");
                }
            }
        }

        public override void ChannelInactive(IChannelHandlerContext context)
        {
            base.ChannelInactive(context);
            Console.WriteLine("inactive");
        }

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