• SuperSocket中的Server是如何初Initialize的


    第一个函数

    d:sourcecodegithubsupersocketquickstartasic elnetserver_startbyconfigprogram.cs

    static void Main(string[] args)
            {
                Console.WriteLine("Press any key to start the server!");
    
                Console.ReadKey();
                Console.WriteLine();
    
                var bootstrap = BootstrapFactory.CreateBootstrap();
    
                if (!bootstrap.Initialize())
                {
                    Console.WriteLine("Failed to initialize!");
                    Console.ReadKey();
                    return;
                }
    
                var result = bootstrap.Start();
    
                Console.WriteLine("Start result: {0}!", result);
    
                if (result == StartResult.Failed)
                {
                    Console.WriteLine("Failed to start!");
                    Console.ReadKey();
                    return;
                }
    
                Console.WriteLine("Press key 'q' to stop it!");
    
                while (Console.ReadKey().KeyChar != 'q')
                {
                    Console.WriteLine();
                    continue;
                }
    
                Console.WriteLine();
    
                //Stop the appServer
                bootstrap.Stop();
    
                Console.WriteLine("The server was stopped!");
            }

    第二个函数

    d:sourcecodegithubsupersocketsocketenginedefaultbootstrap.cs

        /// <summary>
            /// Initializes the bootstrap with the configuration
            /// </summary>
            /// <returns></returns>
            public virtual bool Initialize()
            {
                return Initialize(c => c);
            }

    第三个函数

    d:sourcecodegithubsupersocketsocketenginedefaultbootstrap.cs

            /// <summary>
            /// Initializes the bootstrap with the configuration and config resolver.
            /// </summary>
            /// <param name="serverConfigResolver">The server config resolver.</param>
            /// <returns></returns>
            public virtual bool Initialize(Func<IServerConfig, IServerConfig> serverConfigResolver)
            {
                return Initialize(serverConfigResolver, null);
            }

    第四个函数

    d:sourcecodegithubsupersocketsocketenginedefaultbootstrap.cs

     /// <summary>
            /// Initializes the bootstrap with the configuration, config resolver and log factory.
            /// </summary>
            /// <param name="serverConfigResolver">The server config resolver.</param>
            /// <param name="logFactory">The log factory.</param>
            /// <returns></returns>
            public virtual bool Initialize(Func<IServerConfig, IServerConfig> serverConfigResolver, ILogFactory logFactory)
            {
                if (m_Initialized)
                    throw new Exception("The server had been initialized already, you cannot initialize it again!");
    
                if (logFactory != null && !string.IsNullOrEmpty(m_Config.LogFactory))
                {
                    throw new ArgumentException("You cannot pass in a logFactory parameter, if you have configured a root log factory.", "logFactory");
                }
    
                IEnumerable<WorkItemFactoryInfo> workItemFactories;
    
                using (var factoryInfoLoader = GetWorkItemFactoryInfoLoader(m_Config, logFactory))
                {
                    var bootstrapLogFactory = factoryInfoLoader.GetBootstrapLogFactory();
    
                    logFactory = bootstrapLogFactory.ExportFactory.CreateExport<ILogFactory>();
    
                    LogFactory = logFactory;
                    m_GlobalLog = logFactory.GetLog(this.GetType().Name);
    
                    AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
    
                    try
                    {
                        workItemFactories = factoryInfoLoader.LoadResult(serverConfigResolver);
                    }
                    catch (Exception e)
                    {
                        if (m_GlobalLog.IsErrorEnabled)
                            m_GlobalLog.Error(e);
    
                        return false;
                    }
                }
    
                m_AppServers = new List<IWorkItem>(m_Config.Servers.Count());
    
                IWorkItem serverManager = null;
    
                //Initialize servers
                foreach (var factoryInfo in workItemFactories)
                {
                    IWorkItem appServer = InitializeAndSetupWorkItem(factoryInfo);
    
                    if (appServer == null)
                        return false;
    
                    if (factoryInfo.IsServerManager)
                        serverManager = appServer;
                    else if (!(appServer is IsolationAppServer))//No isolation
                    {
                        //In isolation mode, cannot check whether is server manager in the factory info loader
                        if (TypeValidator.IsServerManagerType(appServer.GetType()))
                            serverManager = appServer;
                    }
    
                    m_AppServers.Add(appServer);
                }
    
                if (serverManager != null)
                    m_ServerManager = serverManager;
    
                if (!m_Config.DisablePerformanceDataCollector)
                {
                    m_PerfMonitor = new PerformanceMonitor(m_Config, m_AppServers, serverManager, logFactory);
    
                    if (m_GlobalLog.IsDebugEnabled)
                        m_GlobalLog.Debug("The PerformanceMonitor has been initialized!");
                }
    
                if (m_GlobalLog.IsDebugEnabled)
                    m_GlobalLog.Debug("The Bootstrap has been initialized!");
    
                try
                {
                    RegisterRemotingService();
                }
                catch (Exception e)
                {
                    if (m_GlobalLog.IsErrorEnabled)
                        m_GlobalLog.Error("Failed to register remoting access service!", e);
    
                    return false;
                }
    
                m_Initialized = true;
    
                return true;
            }

    第五个函数

    d:sourcecodegithubsupersocketsocketenginedefaultbootstrap.cs

    private IWorkItem InitializeAndSetupWorkItem(WorkItemFactoryInfo factoryInfo)
            {
                IWorkItem appServer;
    
                try
                {
                    appServer = CreateWorkItemInstance(factoryInfo.ServerType, factoryInfo.StatusInfoMetadata);
    
                    if (m_GlobalLog.IsDebugEnabled)
                        m_GlobalLog.DebugFormat("The server instance {0} has been created!", factoryInfo.Config.Name);
                }
                catch (Exception e)
                {
                    if (m_GlobalLog.IsErrorEnabled)
                        m_GlobalLog.Error(string.Format("Failed to create server instance {0}!", factoryInfo.Config.Name), e);
                    return null;
                }
    
                var exceptionSource = appServer as IExceptionSource;
    
                if (exceptionSource != null)
                    exceptionSource.ExceptionThrown += new EventHandler<ErrorEventArgs>(exceptionSource_ExceptionThrown);
    
    
                var setupResult = false;
    
                try
                {
                    setupResult = SetupWorkItemInstance(appServer, factoryInfo);
    
                    if (m_GlobalLog.IsDebugEnabled)
                        m_GlobalLog.DebugFormat("The server instance {0} has been initialized!", appServer.Name);
                }
                catch (Exception e)
                {
                    m_GlobalLog.Error(e);
                    setupResult = false;
                }
    
                if (!setupResult)
                {
                    if (m_GlobalLog.IsErrorEnabled)
                        m_GlobalLog.Error("Failed to setup server instance!");
    
                    return null;
                }
    
                return appServer;
            }

    第六个函数

    d:sourcecodegithubsupersocketsocketenginedefaultbootstrap.cs

       internal virtual bool SetupWorkItemInstance(IWorkItem workItem, WorkItemFactoryInfo factoryInfo)
            {
                try
                {
                    //Share AppDomain AppServers also share same socket server factory and log factory instances
                    factoryInfo.SocketServerFactory.ExportFactory.EnsureInstance();
                    factoryInfo.LogFactory.ExportFactory.EnsureInstance();
                }
                catch (Exception e)
                {
                    if (m_GlobalLog.IsErrorEnabled)
                        m_GlobalLog.Error(e);
    
                    return false;
                }
    
                return workItem.Setup(this, factoryInfo.Config, factoryInfo.ProviderFactories.ToArray());
            }

    第七个函数

    d:sourcecodegithubsupersocketsocketbaseappserverbase.cs

            /// <summary>
            /// Setups the specified root config.
            /// </summary>
            /// <param name="bootstrap">The bootstrap.</param>
            /// <param name="config">The socket server instance config.</param>
            /// <param name="factories">The factories.</param>
            /// <returns></returns>
            bool IWorkItem.Setup(IBootstrap bootstrap, IServerConfig config, ProviderFactoryInfo[] factories)
            {
                if (bootstrap == null)
                    throw new ArgumentNullException("bootstrap");
    
                Bootstrap = bootstrap;
    
                if (factories == null)
                    throw new ArgumentNullException("factories");
    
                TrySetInitializedState();
    
                var rootConfig = bootstrap.Config;
    
                SetupBasic(rootConfig, config, GetSingleProviderInstance<ISocketServerFactory>(factories, ProviderKey.SocketServerFactory));
    
                if (!SetupLogFactory(GetSingleProviderInstance<ILogFactory>(factories, ProviderKey.LogFactory)))
                    return false;
    
                Logger = CreateLogger(this.Name);
    
                IEnumerable<IConnectionFilter> connectionFilters = null;
    
                if (!TryGetProviderInstances(factories, ProviderKey.ConnectionFilter, null,
                        (p, f) =>
                        {
                            var ret = p.Initialize(f.Name, this);
    
                            if(!ret)
                            {
                                Logger.ErrorFormat("Failed to initialize the connection filter: {0}.", f.Name);
                            }
    
                            return ret;
                        }, out connectionFilters))
                {
                    return false;
                }
    
                if (!SetupMedium(
                        GetSingleProviderInstance<IReceiveFilterFactory<TRequestInfo>>(factories, ProviderKey.ReceiveFilterFactory),
                        connectionFilters,
                        GetProviderInstances<ICommandLoader<ICommand<TAppSession, TRequestInfo>>>(
                                factories,
                                ProviderKey.CommandLoader,
                                (t) => Activator.CreateInstance(t.MakeGenericType(typeof(ICommand<TAppSession, TRequestInfo>))))))
                {
                    return false;
                }
    
                if (!SetupAdvanced(config))
                    return false;
    
                if (!Setup(rootConfig, config))
                    return false;
    
                if (!SetupFinal())
                    return false;
    
                m_StateCode = ServerStateConst.NotStarted;
                return true;
            }

    第八个函数

    d:sourcecodegithubsupersocketsocketbaseappserverbase.cs

         private bool SetupFinal()
            {
                //Check receiveFilterFactory
                if (ReceiveFilterFactory == null)
                {
                    ReceiveFilterFactory = CreateDefaultReceiveFilterFactory();
    
                    if (ReceiveFilterFactory == null)
                    {
                        if (Logger.IsErrorEnabled)
                            Logger.Error("receiveFilterFactory is required!");
    
                        return false;
                    }
                }
    
                var plainConfig = Config as ServerConfig;
    
                if (plainConfig == null)
                {
                    //Using plain config model instead of .NET configuration element to improve performance
                    plainConfig = new ServerConfig(Config);
    
                    if (string.IsNullOrEmpty(plainConfig.Name))
                        plainConfig.Name = Name;
    
                    Config = plainConfig;
                }
    
                try
                {
                    m_ServerStatus = new StatusInfoCollection();
                    m_ServerStatus.Name = Name;
                    m_ServerStatus.Tag = Name;
                    m_ServerStatus[StatusInfoKeys.MaxConnectionNumber] = Config.MaxConnectionNumber;
                    m_ServerStatus[StatusInfoKeys.Listeners] = m_Listeners;
                }
                catch (Exception e)
                {
                    if (Logger.IsErrorEnabled)
                        Logger.Error("Failed to create ServerSummary instance!", e);
    
                    return false;
                }
    
                return SetupSocketServer();
            }

    第九个函数

    d:sourcecodegithubsupersocketsocketbaseappserverbase.cs

      /// <summary>
            /// Setups the socket server.instance
            /// </summary>
            /// <returns></returns>
            private bool SetupSocketServer()
            {
                try
                {
                    m_SocketServer = m_SocketServerFactory.CreateSocketServer<TRequestInfo>(this, m_Listeners, Config);
                    return m_SocketServer != null;
                }
                catch (Exception e)
                {
                    if (Logger.IsErrorEnabled)
                        Logger.Error(e);
    
                    return false;
                }
            }

    第十个函数

    d:sourcecodegithubsupersocketsocketenginesocketserverfactory.cs

     /// <summary>
        /// Default socket server factory
        /// </summary>
        public class SocketServerFactory : ISocketServerFactory
        {
            #region ISocketServerFactory Members
    
            /// <summary>
            /// Creates the socket server.
            /// </summary>
            /// <typeparam name="TRequestInfo">The type of the request info.</typeparam>
            /// <param name="appServer">The app server.</param>
            /// <param name="listeners">The listeners.</param>
            /// <param name="config">The config.</param>
            /// <returns></returns>
            public ISocketServer CreateSocketServer<TRequestInfo>(IAppServer appServer, ListenerInfo[] listeners, IServerConfig config)
                where TRequestInfo : IRequestInfo
            {
                if (appServer == null)
                    throw new ArgumentNullException("appServer");
    
                if (listeners == null)
                    throw new ArgumentNullException("listeners");
    
                if (config == null)
                    throw new ArgumentNullException("config");
    
                switch(config.Mode)
                {
                    case(SocketMode.Tcp):
                        return new AsyncSocketServer(appServer, listeners);
                    case(SocketMode.Udp):
                        return new UdpSocketServer<TRequestInfo>(appServer, listeners);
                    default:
                        throw new NotSupportedException("Unsupported SocketMode:" + config.Mode);
                }
            }
    
            #endregion
        }
  • 相关阅读:
    jdk1.5线程知识列表
    linux 常用命令记录
    spring batch 编码问题
    maven
    统计文本中每个单词出现的次数
    生成优惠券,并将优惠券存入Mysql
    python 2.7版本解决TypeError: 'encoding' is an invalid keyword argument for this function
    CSRF verification failed. Request aborted. 表单提交方法为POST时的报错
    InsecureRequestWarning: Unverified HTTPS request is being made.解决方法
    SQL Server 打印九九乘法表
  • 原文地址:https://www.cnblogs.com/chucklu/p/5265384.html
Copyright © 2020-2023  润新知