using System; using DotNetty.Codecs.Http; using DotNetty.Common.Internal.Logging; using DotNetty.Handlers.Logging; using DotNetty.Handlers.Streams; using DotNetty.Handlers.Timeout; using DotNetty.Transport.Bootstrapping; using DotNetty.Transport.Channels; using DotNetty.Transport.Channels.Sockets; using log4net; using Microsoft.Extensions.Logging; using LogLevel = DotNetty.Handlers.Logging.LogLevel; namespace BrakeMachine.Brack { public class BrackService: IDisposable { private static readonly ILog Log = LogManager.GetLogger(typeof(BrackService)); private static MultithreadEventLoopGroup? bossGroup; private static MultithreadEventLoopGroup? workerGroup; private static ServerBootstrap? bootstrap; public LogLevel? LogLevel { get; set; } private void InitBootstrap() { if (LogLevel != null) { InternalLoggerFactory.DefaultFactory.AddProvider(new Log4NetProvider()); } bossGroup = new MultithreadEventLoopGroup(); workerGroup = new MultithreadEventLoopGroup(); bootstrap = new ServerBootstrap(); bootstrap .Group(bossGroup, workerGroup) // 设置主和工作线程组 .Channel() // 设置通道模式为TcpSocket .Option(ChannelOption.SoKeepalive, true) //保持连接 .Handler(new LoggingHandler()) .ChildHandler(new ActionChannelInitializer(channel => { var pipeline = channel.Pipeline; pipeline.AddLast(new LoggingHandler()); //业务handler ,这里是实际处理业务的Handler pipeline.AddLast(new HttpServerCodec()); pipeline.AddLast(new HttpHandler()); })); } public void Start(int port = 9001) { if (bossGroup == null) { InitBootstrap(); } BrackMgr.Connect(); IChannel channel = bootstrap.BindAsync(port).Result; Log.Info($"server listen {port}"); } public void Dispose() { bossGroup.ShutdownGracefullyAsync().Wait(); workerGroup.ShutdownGracefullyAsync().Wait(); } } }