// //==================================================================================================== /// <summary> /// coreClass constructor for app, non-Internet use. coreClass is the primary object internally, created by cp. /// </summary> /// <param name="cp"></param> /// <remarks></remarks> public CoreController(CPClass cp, string applicationName, ServerConfigModel serverConfig) { try { cpParent = cp; deleteSessionOnExit = true; _mockNow = null; LogController.log(this, "CoreController constructor-2, enter", BaseClasses.CPLogBaseClass.LogLevel.Trace); // metaDataDictionary = new Dictionary <string, Models.Domain.ContentMetadataModel>(); tableSchemaDictionary = null; // // -- create default auth objects for non-user methods, or until auth is available session = new SessionController(this); // this.serverConfig = serverConfig; this.serverConfig.defaultDataSourceType = ServerConfigBaseModel.DataSourceTypeEnum.sqlServer; appConfig = AppConfigModel.getObject(this, serverConfig, applicationName); appConfig.appStatus = AppConfigModel.AppStatusEnum.ok; webServer.iisContext = null; constructorInitialize(false); LogController.log(this, "CoreController constructor-2, exit", BaseClasses.CPLogBaseClass.LogLevel.Trace); } catch (Exception ex) { LogController.logLocalOnly("CoreController constructor-2, exception [" + ex.ToString() + "]", BaseClasses.CPLogBaseClass.LogLevel.Fatal); throw; } }
/// <inheritdoc /> /// <summary> /// Initializes a new instance of the <see cref="T:HiLoSocket.SocketApp.Server`1" /> class. /// </summary> /// <param name="serverConfigModel">The server model.</param> /// <param name="logger">The logger.</param> /// <exception cref="T:System.ArgumentNullException">serverConfigModel</exception> /// <exception cref="T:System.ComponentModel.DataAnnotations.ValidationException"></exception> internal Server(ServerConfigModel serverConfigModel, ILogger logger) : base(serverConfigModel?.FormatterType, serverConfigModel?.CompressType, logger) { CheckIfNullInput(serverConfigModel); ValidateInputModel(serverConfigModel); LocalIpEndPoint = serverConfigModel?.LocalIpEndPoint; }
// //==================================================================================================== /// <summary> /// coreClass constructor for a web request/response environment. coreClass is the primary object internally, created by cp. /// </summary> public CoreController(CPClass cp, string applicationName, System.Web.HttpContext httpContext) { try { this.cpParent = cp; this.cpParent.core = this; _mockNow = null; LogController.log(this, "CoreController constructor-4, enter", BaseClasses.CPLogBaseClass.LogLevel.Trace); // metaDataDictionary = new Dictionary <string, Models.Domain.ContentMetadataModel>(); tableSchemaDictionary = null; // // -- create default auth objects for non-user methods, or until auth is available session = new SessionController(this); // serverConfig = ServerConfigModel.getObject(this); serverConfig.defaultDataSourceType = ServerConfigBaseModel.DataSourceTypeEnum.sqlServer; appConfig = AppConfigModel.getObject(this, serverConfig, applicationName); if (appConfig != null) { webServer.initWebContext(httpContext); constructorInitialize(true); } LogController.log(this, "CoreController constructor-4, exit", BaseClasses.CPLogBaseClass.LogLevel.Trace); } catch (Exception ex) { LogController.logLocalOnly("CoreController constructor-4, exception [" + ex.ToString() + "]", BaseClasses.CPLogBaseClass.LogLevel.Fatal); throw; } }
private static void ValidateInputModel(ServerConfigModel serverConfigModel) { if (serverConfigModel.ValidateObject(out var errorMessages) == false) { throw new ValidationException($@"時間 : {DateTime.Now.GetDateTimeString( )}, 類別 : {nameof( Server<TCommandModel> )}, 方法 : Constructor, 內容 : {string.Join( "\n", errorMessages )}"); } }
private static void CheckIfNullInput(ServerConfigModel serverConfigModel) { if (serverConfigModel == null) { throw new ArgumentNullException(nameof(serverConfigModel), $@"時間 : {DateTime.Now.GetDateTimeString( )}, 類別 : {nameof( Server<TCommandModel> )}, 方法 : Constructor, 內容 : 你沒初始化 {nameof( serverConfigModel )} 喔。"); } }
// //==================================================================================================== /// <summary> /// coreClass constructor for cluster use. /// </summary> /// <param name="cp"></param> /// <remarks></remarks> public CoreController(CPClass cp) { cpParent = cp; _mockNow = null; deleteSessionOnExit = true; LogController.log(this, "CoreController constructor-0, enter", BaseClasses.CPLogBaseClass.LogLevel.Trace); // metaDataDictionary = new Dictionary <string, ContentMetadataModel>(); tableSchemaDictionary = null; // // -- create default auth objects for non-user methods, or until auth is available session = new SessionController(this); // serverConfig = ServerConfigModel.getObject(this); this.serverConfig.defaultDataSourceType = ServerConfigBaseModel.DataSourceTypeEnum.sqlServer; webServer.iisContext = null; constructorInitialize(false); LogController.log(this, "CoreController constructor-0, exit", BaseClasses.CPLogBaseClass.LogLevel.Trace); }
// //==================================================================================================== /// <summary> /// coreClass constructor for app, non-Internet use. coreClass is the primary object internally, created by cp. /// </summary> /// <param name="cp"></param> /// <remarks></remarks> public CoreController(CPClass cp, string applicationName, ServerConfigModel serverConfig, System.Web.HttpContext httpContext) { try { this.cpParent = cp; this.cpParent.core = this; _mockNow = null; deleteSessionOnExit = false; LogController.log(this, "CoreController constructor-3, enter", BaseClasses.CPLogBaseClass.LogLevel.Trace); // // -- create default auth objects for non-user methods, or until auth is available session = new SessionController(this); // this.serverConfig = serverConfig; this.serverConfig.defaultDataSourceType = ServerConfigBaseModel.DataSourceTypeEnum.sqlServer; appConfig = AppConfigModel.getObject(this, serverConfig, applicationName); this.appConfig.appStatus = AppConfigModel.AppStatusEnum.ok; webServer.initWebContext(httpContext); constructorInitialize(true); LogController.log(this, "CoreController constructor-3, exit", BaseClasses.CPLogBaseClass.LogLevel.Trace); } catch (Exception ex) { LogController.logLocalOnly("CoreController constructor-3, exception [" + ex.ToString() + "]", BaseClasses.CPLogBaseClass.LogLevel.Fatal); throw; } }
public async Task RunServerAsync(ServerConfigModel configModel) { Console.WriteLine("WebSocket服务器启动"); Console.WriteLine( $"系统版本:{RuntimeInformation.OSArchitecture} {RuntimeInformation.OSDescription}\r\n" + $".NET版本:{RuntimeInformation.ProcessArchitecture} {RuntimeInformation.FrameworkDescription}\r\n" + $"CPU核心数:{Environment.ProcessorCount}"); Console.WriteLine("传输类型:" + (configModel.UserLibuv ? "Libuv" : "Socket")); if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { GCSettings.LatencyMode = GCLatencyMode.SustainedLowLatency; } Console.WriteLine($"服务器垃圾回收机制:{(GCSettings.IsServerGC ? "启用" : "禁用")}"); Console.WriteLine($"垃圾回收延迟模式:{GCSettings.LatencyMode}"); IEventLoopGroup bossGroup; IEventLoopGroup workGroup; if (configModel.UserLibuv) { var dispatcher = new DispatcherEventLoopGroup(); bossGroup = dispatcher; workGroup = new WorkerEventLoopGroup(dispatcher); } else { bossGroup = new MultithreadEventLoopGroup(1); workGroup = new MultithreadEventLoopGroup(); } X509Certificate2 tlsCertificate = null; if (configModel.IsSsl) { tlsCertificate = new X509Certificate2(configModel.CertificatePath, configModel.CertificatePassword); } try { var bootstrap = new ServerBootstrap(); bootstrap.Group(bossGroup, workGroup); if (configModel.UserLibuv) { bootstrap.Channel <TcpServerChannel>(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { bootstrap.Option(ChannelOption.SoReuseport, true) .ChildOption(ChannelOption.SoReuseaddr, true); } } else { bootstrap.Channel <TcpServerSocketChannel>(); } bootstrap.Option(ChannelOption.SoBacklog, 8192) .ChildHandler(new ActionChannelInitializer <IChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; if (tlsCertificate != null) { pipeline.AddLast(TlsHandler.Server(tlsCertificate)); } pipeline.AddLast(new HttpServerCodec()); pipeline.AddLast(new HttpObjectAggregator(65536)); if (configModel.ServerHandler is BaseDotNettyServerHandler serverHandler) { pipeline.AddLast(serverHandler); } })); IPAddress iPAddress = IPAddress.Parse(configModel.Host); IChannel bootstrapChannel = await bootstrap.BindAsync(iPAddress, configModel.Port); Console.WriteLine("打开你的浏览器跳转到:" + $"{(configModel.IsSsl ? "https" : "http")}" + $"://{iPAddress}:{configModel.Port}/api"); Console.WriteLine("监听中:" + $"{(configModel.IsSsl ? "wss" : "ws")}" + $"://{iPAddress}:{configModel.Port}/websocket"); Console.ReadLine(); await bootstrapChannel.CloseAsync(); } finally { workGroup.ShutdownGracefullyAsync().Wait(); bossGroup.ShutdownGracefullyAsync().Wait(); } }
/// <inheritdoc /> /// <summary> /// Initializes a new instance of the <see cref="T:HiLoSocket.SocketApp.Server`1" /> class. /// </summary> /// <param name="serverConfigModel">The server model.</param> internal Server(ServerConfigModel serverConfigModel) : this(serverConfigModel, null) { }
// //==================================================================================================== /// <summary> /// create a new app. Must run in in task-service with elevated permissions /// </summary> /// <param name="cp"></param> /// <returns></returns> public override object Execute(Contensive.BaseClasses.CPBaseClass cpRootApp) { try { string appName = cpRootApp.Doc.GetText("appName"); string domainName = cpRootApp.Doc.GetText("domainName"); // using (CPClass cpServer = new CPClass()) { AppConfigModel appConfig = new AppConfigModel { // // -- enable it enabled = true, // // -- private key privateKey = Processor.Controllers.GenericController.getGUIDNaked(), // // -- allow site monitor allowSiteMonitor = false, name = appName, // // -- admin route adminRoute = "admin" }; // // -- domain domainName = "www." + appConfig.name + ".com"; appConfig.domainList.Add(domainName); // // -- file architectur appConfig.localWwwPath = cpServer.core.serverConfig.localDataDriveLetter + ":\\inetpub\\" + appConfig.name + "\\www\\"; appConfig.localFilesPath = cpServer.core.serverConfig.localDataDriveLetter + ":\\inetpub\\" + appConfig.name + "\\files\\"; appConfig.localPrivatePath = cpServer.core.serverConfig.localDataDriveLetter + ":\\inetpub\\" + appConfig.name + "\\private\\"; appConfig.localTempPath = cpServer.core.serverConfig.localDataDriveLetter + ":\\inetpub\\" + appConfig.name + "\\temp\\"; if (cpServer.core.serverConfig.isLocalFileSystem) { // // -- no prompts, local file system appConfig.remoteWwwPath = ""; appConfig.remoteFilePath = ""; appConfig.remotePrivatePath = ""; appConfig.cdnFileUrl = "/" + appConfig.name + "/files/"; } else { // // -- no prompts, remote file system appConfig.remoteWwwPath = "/" + appConfig.name + "/www/"; appConfig.remoteFilePath = "/" + appConfig.name + "/files/"; appConfig.remotePrivatePath = "/" + appConfig.name + "/private/"; appConfig.cdnFileUrl = "https://s3.amazonaws.com/" + cpServer.core.serverConfig.awsBucketName + "/" + appConfig.name + "/files/"; } Contensive.Processor.Controllers.LogController.logInfo(cpServer.core, "Create local folders."); setupDirectory(appConfig.localWwwPath); setupDirectory(appConfig.localFilesPath); setupDirectory(appConfig.localPrivatePath); setupDirectory(appConfig.localTempPath); // // -- save the app configuration and reload the server using this app Contensive.Processor.Controllers.LogController.logInfo(cpServer.core, "Save app configuration."); appConfig.appStatus = AppConfigModel.AppStatusEnum.maintenance; cpServer.core.serverConfig.apps.Add(appConfig.name, appConfig); cpServer.core.serverConfig.save(cpServer.core); cpServer.core.serverConfig = ServerConfigModel.getObject(cpServer.core); cpServer.core.appConfig = AppConfigModel.getObject(cpServer.core, cpServer.core.serverConfig, appConfig.name); // // update local host file // try { LogController.logInfo(cpServer.core, "Update host file to add domain [127.0.0.1 " + appConfig.name + "]."); File.AppendAllText("c:\\windows\\system32\\drivers\\etc\\hosts", System.Environment.NewLine + "127.0.0.1\t" + appConfig.name); } catch (Exception ex) { LogController.logWarn(cpServer.core, "Error attempting to update local host file:" + ex); LogController.logWarn(cpServer.core, "Please manually add the following line to your host file (c:\\windows\\system32\\drivers\\etc\\hosts):" + "127.0.0.1\t" + appConfig.name); } // // create the database on the server // LogController.logInfo(cpServer.core, "Create database."); cpServer.core.dbServer.createCatalog(appConfig.name); } // // initialize the new app, use the save authentication that was used to authorize this object // using (CPClass cp = new CPClass(appName)) { LogController.logInfo(cp.core, "Verify website."); // const string iisDefaultDoc = "default.aspx"; cp.core.webServer.verifySite(appName, domainName, cp.core.appConfig.localWwwPath, iisDefaultDoc); // LogController.logInfo(cp.core, "Run db upgrade."); BuildController.upgrade(cp.core, true, true); // // -- set the application back to normal mode cp.core.serverConfig.save(cp.core); cp.core.siteProperties.setProperty(Constants.siteproperty_serverPageDefault_name, iisDefaultDoc); // LogController.logInfo(cp.core, "Upgrade complete."); LogController.logInfo(cp.core, "Use IIS Import Application to install either you web application, or the Contensive IISDefault.zip application."); } // return(string.Empty); } catch (Exception ex) { cpRootApp.Site.ErrorReport(ex); return("ERROR, unexpected exception during NewApp"); } }
// //========================================================================================================= /// <summary> /// constructor for iis site use. Configuration provided manually (maybe from webconfig) /// </summary> /// <param name="httpContext"></param> /// <remarks></remarks> public CPClass(string appName, ServerConfigModel serverConfig, System.Web.HttpContext httpContext) { core = new CoreController(this, appName, serverConfig, httpContext); }
// //========================================================================================================= /// <summary> /// constructor for non-Internet app use. Configuration provided manually /// </summary> /// <remarks></remarks> public CPClass(string appName, ServerConfigModel serverConfig) { core = new CoreController(this, appName, serverConfig); }