using DotNetty.Codecs; using DotNetty.Transport.Bootstrapping; using DotNetty.Transport.Channels; using DotNetty.Transport.Channels.Sockets; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using NearCardAttendance.Common; using NearCardAttendance.Common.helper; using NearCardAttendance.Service.TcpServer.Handler; using NearCardAttendance.Service.TcpServer.Mapper; using NearCardAttendance.TcpServer.Config; using Serilog; using System.Text; namespace NearCardAttendance.TcpServer { internal class Program { static void Main(string[] args) { var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .Build(); Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(config).Enrich.WithThreadInfo() .Filter.ByExcluding(logEvent => logEvent.Level == Serilog.Events.LogEventLevel.Verbose) // 过滤掉VRB级别的日志 .CreateLogger(); try { Log.Information("Starting up"); CreateHostBuilder(args).Build().Run(); } catch (Exception ex) { Log.Fatal(ex, "Application start-up failed"); } finally { Log.CloseAndFlush(); } } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseSerilog() .ConfigureServices((hostContext, services) => { var configuration = hostContext.Configuration; #region 配置信息 //services // .Configure(configuration.GetSection("ServiceConfig")) // ; #endregion #region Http请求 services .AddSingleton() .AddHttpClient(Consts.DEFAULT_HTTPCLIENT_NAME, c => { c.Timeout = TimeSpan.FromSeconds(10); //超时限制 c.DefaultRequestHeaders.Add("Accept", "application/json"); }) ; #endregion #region TcpService services .AddSingleton(provider => { var bossGroup = new MultithreadEventLoopGroup(); var workerGroup = new MultithreadEventLoopGroup(); var bootstrap = new ServerBootstrap(); bootstrap.Group(bossGroup, workerGroup) .Channel() .Option(ChannelOption.SoBacklog, 100) .ChildOption(ChannelOption.TcpNodelay, true) // 低延迟 .ChildHandler(new ActionChannelInitializer(channel => { // var handler = provider.GetRequiredService(); // var handler = provider.GetRequiredService(); var pipeline = channel.Pipeline; pipeline.AddLast(new StringEncoder(Encoding.ASCII)); pipeline.AddLast( provider.GetRequiredService(), provider.GetRequiredService() //provider.GetRequiredService(), //provider.GetRequiredService() ); // Add the injected handler })); return bootstrap; }) .AddSingleton() .AddSingleton() .AddTransient() .AddTransient() //.AddTransient() //.AddTransient() .AddHostedService() ; #endregion }); } }