static ConfigUtil()
        {
            ServerConfig = new FileSystemConfig(BootstrapPath);
            ServerConfig.Initialize();

            ClientConfig = new FakeClientConfig();
        }
        /// <summary>
        /// 启动监听
        /// </summary>
        /// <param name="config">服务器配置</param>
        /// <returns></returns>
        public override bool Start(IServerConfig config)
        {
            m_ListenSocket = new System.Net.Sockets.Socket(this.Info.EndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                //关联终结地
                m_ListenSocket.Bind(this.Info.EndPoint);
                //设置监听最大连接数
                m_ListenSocket.Listen(m_ListenBackLog);

                m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);

                m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
                //初始化套接字操作
                SocketAsyncEventArgs acceptEventArg = new SocketAsyncEventArgs();
                m_AcceptSAE = acceptEventArg;
                //定义一个连接完成事件
                acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(acceptEventArg_Completed);
                if (!m_ListenSocket.AcceptAsync(acceptEventArg))
                {
                    ProcessAccept(acceptEventArg);
                }
                return true;
            }
            catch (Exception e)
            {
                OnError(e);
                return false;
            }
        }
Example #3
0
        public virtual bool Setup(IBootstrap bootstrap, IServerConfig config)
        {
            Bootstrap = bootstrap;

            var loggerProvider = bootstrap as ILoggerProvider;

            if (loggerProvider != null)
                Logger = loggerProvider.Logger;

            State = ServerState.Initializing;
            Config = config;
            Name = config.Name;            
            State = ServerState.NotStarted;

            AppWorkingDir = config.Options.Get("appWorkingDir") ?? GetAppWorkingDir(Name);

            if (!Directory.Exists(AppWorkingDir))
                Directory.CreateDirectory(AppWorkingDir);

            var appConfigFilePath = GetAppConfigFile();

            // use the application's own config file if it has
            //AppRoot\AppName\App.config
            if (!string.IsNullOrEmpty(appConfigFilePath))
                StartupConfigFile = appConfigFilePath;

            m_NotStartedStatus = new Lazy<StatusInfoCollection>(() =>
                {
                    var status = new StatusInfoCollection(m_Metadata.Name);
                    status[StatusInfoKeys.IsRunning] = false;
                    return status;
                });

            return true;
        }
		public void SetUp() {
			serverConfig = A.Fake<IServerConfig>();
			directoryEntryFactory = A.Fake<IDirectoryEntryFactory>();
			filterBuilde = new FilterBuilder(serverConfig);
			nameParser = new NameParser();
			adapter = new DirectoryEntryAdapter(serverConfig, directoryEntryFactory, filterBuilde, nameParser);
		}
Example #5
0
        protected override AppServerMetadata GetAppServerMetadata(IServerConfig serverConfig)
        {
            AppDomain validateDomain = null;
            AppServerMetadata metadata = null;

            try
            {
                validateDomain = AppDomain.CreateDomain("ValidationDomain", AppDomain.CurrentDomain.Evidence, serverConfig.Options.Get("appWorkingDir") ?? IsolationApp.GetAppWorkingDir(serverConfig.Name), string.Empty, false);

                AssemblyImport.RegisterAssembplyImport(validateDomain);

                validateDomain.SetData(typeof(IsolationMode).Name, ConfigSource.Isolation);

                var validatorType = typeof(RemoteAppTypeValidator);
                var validator = (RemoteAppTypeValidator)validateDomain.CreateInstanceAndUnwrap(validatorType.Assembly.FullName, validatorType.FullName);

                var result = validator.GetServerMetadata(serverConfig.Type);

                if(!result.Result)
                {
                    Logger.Error(result.Message);
                    return null;
                }

                metadata = result.Value;
            }
            finally
            {
                if (validateDomain != null)
                    AppDomain.Unload(validateDomain);
            }

            return metadata;
        }
        /// <summary>
        /// Starts to listen
        /// </summary>
        /// <param name="config">The server config.</param>
        /// <returns></returns>
        public override bool Start(IServerConfig config)
        {
            try
            {
                m_ListenSocket = new Socket(this.EndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
                m_ListenSocket.Bind(this.EndPoint);

                uint IOC_IN = 0x80000000;
                uint IOC_VENDOR = 0x18000000;
                uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;

                byte[] optionInValue = { Convert.ToByte(false) };
                byte[] optionOutValue = new byte[4];
                m_ListenSocket.IOControl((int)SIO_UDP_CONNRESET, optionInValue, optionOutValue);

                var eventArgs = new SocketAsyncEventArgs();

                eventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(eventArgs_Completed);
                eventArgs.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0);

                int receiveBufferSize = config.ReceiveBufferSize <= 0 ? 2048 : config.ReceiveBufferSize;
                var buffer = new byte[receiveBufferSize];
                eventArgs.SetBuffer(buffer, 0, buffer.Length);

                m_ListenSocket.ReceiveFromAsync(eventArgs);

                return true;
            }
            catch (Exception e)
            {
                OnError(e);
                return false;
            }
        }
        public override bool Init(FtpServer server, IServerConfig config)
        {
            if (!base.Init(server, config))
                return false;

            var userSettingFile = config.Options.GetValue("userSetting");            

            if (string.IsNullOrEmpty(userSettingFile))
            {
                server.Logger.Error("No user setting file was not defined!");
                return false;
            }

            if (!Path.IsPathRooted(userSettingFile))
                userSettingFile = server.GetFilePath(userSettingFile);

            if (!File.Exists(userSettingFile))
            {
                AppServer.Logger.Error("The userSetting file cannot be found!");
                return false;
            }

            m_UserConfigFile = userSettingFile;

            ReadUserConfigFile();

            m_UserConfigReadTimer = new Timer(OnUserConfigReadTimerCallback, null, Timeout.Infinite, Timeout.Infinite);

            return true;
        }
 /// <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>
 public bool Setup(IBootstrap bootstrap, IServerConfig config, ProviderFactoryInfo[] factories)
 {
     m_Bootstrap = bootstrap;
     m_ServerConfig = config;
     m_Factories = factories;
     return true;
 }
Example #9
0
 public void ReportPotentialConfigChange(IServerConfig config)
 {
     foreach (var item in Items)
     {
         item.ReportPotentialConfigChange(config);
     }
 }
        /// <summary>
        /// Starts to listen
        /// </summary>
        /// <param name="config">The server config.</param>
        /// <returns></returns>
        public override bool Start(IServerConfig config)
        {
            m_ListenSocket = new Socket(this.Info.EndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                m_ListenSocket.Bind(this.Info.EndPoint);
                m_ListenSocket.Listen(m_ListenBackLog);

                m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
                m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
                //
                m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            
                SocketAsyncEventArgs acceptEventArg = new SocketAsyncEventArgs();
                acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(acceptEventArg_Completed);

                if (!m_ListenSocket.AcceptAsync(acceptEventArg))
                    ProcessAccept(acceptEventArg);

                return true;

            }
            catch (Exception e)
            {
                OnError(e);
                return false;
            }
        }
Example #11
0
        /// <summary>
        /// Starts to listen
        /// </summary>
        /// <param name="config">The server config.</param>
        /// <returns></returns>
        public override bool Start(IServerConfig config)
        {
            try
            {
                m_ListenSocket = new Socket(this.EndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
                m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                m_ListenSocket.Bind(this.EndPoint);

                //Mono doesn't support it
                if (Platform.SupportSocketIOControlByCodeEnum)
                {
                    uint IOC_IN = 0x80000000;
                    uint IOC_VENDOR = 0x18000000;
                    uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;

                    byte[] optionInValue = { Convert.ToByte(false) };
                    byte[] optionOutValue = new byte[4];
                    m_ListenSocket.IOControl((int)SIO_UDP_CONNRESET, optionInValue, optionOutValue);
                }

                var eventArgs = m_SaePool.Get();

                m_ListenSocket.ReceiveFromAsync(eventArgs);

                return true;
            }
            catch (Exception e)
            {
                OnError(e);
                return false;
            }
        }
Example #12
0
        private bool Composite(IServerConfig config)
        {
            CompositionContainer = GetCompositionContainer(config);

            //Fill the imports of this object
            try
            {
                var targets = new List<ICompositeTarget>();
                RegisterCompositeTarget(targets);

                if (targets.Any())
                {
                    foreach (var t in targets)
                    {
                        if(!t.Resolve(this, CompositionContainer))
                        {
                            throw new Exception("Failed to resolve the instance of the type: " + t.GetType().FullName);
                        }
                    }
                }

                return true;
            }
            catch(Exception e)
            {
                var logger = Logger;

                if (logger == null)
                    throw e;

                logger.Error("Composition error", e);
                return false;
            }
        }
Example #13
0
 public ConfigInfo(IServerConfig serverConfig, ClientConfiguration clientConfig)
 {
     ServerConfig = serverConfig;
     ClientConfig = clientConfig;
     CreationTime = DateTime.Now;
     Initialize();
 }
        public void SetUp()
        {
            _clientConfig = new ClientConfiguration();
            _clientConfig.Servers.Add(new Uri("http://127.0.0.1:8091/pools/"));

            _serverConfig = new HttpServerConfig(_clientConfig);
            _serverConfig.Initialize();
        }
Example #15
0
        bool IDynamicBootstrap.AddAndStart(IServerConfig config)
        {
            var newWorkItem = AddNewServer(config);

            if (newWorkItem == null)
                return false;

            return newWorkItem.Start();
        }
        static ConfigUtil()
        {
            EnsureConfigExtracted();

            ServerConfig = new FileSystemConfig(Path.Combine(RelativeConfigurationPath, "bootstrap.json"));
            ServerConfig.Initialize();

            ClientConfig = new FakeClientConfig();
        }
 public IConfigInfo GetConfig(string bucketName)
 {
     if (_serverConfig == null)
     {
         _serverConfig = new FileSystemConfig(_bootstrapPath);
     }
     _configInfo = new ConfigInfo(_serverConfig, _clientConfig);
     return _configInfo;
 }
 internal ClusterManager(ClientConfiguration clientConfig, IServerConfig serverConfig, HttpClient httpClient, IDataMapper mapper, string username, string password)
 {
     _clientConfig = clientConfig;
     _serverConfig = serverConfig;
     Mapper = mapper;
     HttpClient = httpClient;
     _password = password;
     _username = username;
 }
        public void SetUp()
        {
            _serverIp = ConfigurationManager.AppSettings["serverIp"];
            _clientConfig = new ClientConfiguration();
            _clientConfig.Servers.Add(new Uri(string.Format("http://{0}:8091/pools/", _serverIp)));

            _serverConfig = new HttpServerConfig(_clientConfig);
            _serverConfig.Initialize();
        }
Example #20
0
 public GameServer()
 {
     m_Config = DefaultServerConfig;
     m_RootConfig = new RootConfig();
     m_Encoding = new System.Text.UTF8Encoding();
     server = new MyServer();
     server.NewSessionConnected += server_NewSessionConnected;
     server.SessionClosed += server_SessionClosed;
 }
Example #21
0
        protected override IManagedApp CreateAppInstance(IServerConfig serverConfig)
        {
            var appFile = serverConfig.Options.Get("appFile");

            if(string.IsNullOrEmpty(appFile))
                return base.CreateAppInstance(serverConfig);

            var serverMetadata = new ExternalProcessAppServerMetadata(serverConfig.Options.Get("appDir"), appFile, serverConfig.Options.Get("appArgs"));
            return new ExternalProcessApp(serverMetadata, ConfigFilePath);
        }
Example #22
0
        protected override bool Setup(IManagedApp managedApp, IServerConfig config)
        {
            var ret = managedApp.Setup(m_RemoteBootstrapWrap, config);

            if (!ret)
                return false;

            SetupRecycleTriggers(managedApp, config);
            return ret;
        }
        public UdpSocketServerTest()
        {
            m_Config = DefaultServerConfig;
            m_RootConfig = new RootConfig
            {
                LoggingMode = LoggingMode.Console
            };

            m_Encoding = new UTF8Encoding();
        }
Example #24
0
        protected override bool Setup(IManagedApp managedApp, IServerConfig config)
        {
            var ret = base.Setup(managedApp, config);

            if (!ret)
                return false;

            SetupRecycleTriggers(managedApp, config);
            return ret;
        }
Example #25
0
        public bool Setup(string serverType, string bootstrapUri, string assemblyImportRoot, IServerConfig config, ProviderFactoryInfo[] factories)
        {
            m_AssemblyImporter = new AssemblyImport(assemblyImportRoot);

            var serviceType = Type.GetType(serverType);
            m_AppServer = (IWorkItem)Activator.CreateInstance(serviceType);

            var bootstrap = (IBootstrap)Activator.GetObject(typeof(IBootstrap), bootstrapUri);

            return m_AppServer.Setup(bootstrap, config, factories);
        }
Example #26
0
        public Controller(IReworkStation reworkStation, IProgramStorage programStorage, IProgramRunStorage programRunStorage, IServerConfig serverConfig)
        {
            Get["/programs"] = _ =>
            {
                Console.WriteLine("Getting programs.");
                return JArray.FromObject(programStorage.GetPrograms()).ToString();
            };
            Post["/programs"] = _ =>
            {
                Console.WriteLine("Updating programs.");
                programStorage.UpdatePrograms(this.Bind<List<Pc900Program>>());
                return @"{""status"":""OK""}";
            };
            Post["/delete-programs"] = _ =>
            {
                Console.WriteLine("Deleting programs.");
                programStorage.DeletePrograms(this.Bind<List<Pc900Program>>());
                return @"{""status"":""OK""}";
            };
            Post["/start-program/{programId}"] = path =>
            {
                Console.WriteLine("Starting program "+ path.programId.Value + ".");
                var pc900ProgramRuns = programRunStorage.GetProgramRuns();
                if (pc900ProgramRuns.Count > 0)
                {
                    return JObject.FromObject(pc900ProgramRuns[0]).ToString();
                }

                Pc900Program program = programStorage.GetProgram(path.programId.Value);
                var programRun = reworkStation.Start(program);
                programRunStorage.AddProgramRun(programRun);

                var achiPoller = new AchiPoller(reworkStation, programRunStorage);
                _poller = new Timer(poll =>
                {
                    if (achiPoller.PollWorker(null))
                    {
                        _poller.Dispose();
                    }
                }, null, 1000, serverConfig.GetProgramRunPollingIntervalMillis());

                return JObject.FromObject(programRun).ToString();
            };
            Get["/current-run/after-point/{afterPoint}"] = path => JObject.FromObject(programRunStorage.GetProgramRuns()[0].CreatePartial(int.Parse(path.afterPoint.Value))).ToString();
            Get["/current-run"] = _ =>
            {
                var pc900ProgramRuns = programRunStorage.GetProgramRuns();
                if (pc900ProgramRuns.Count > 0)
                {
                    return JObject.FromObject(pc900ProgramRuns[0]).ToString();
                }
                return JObject.FromObject(new Pc900ProgramRun("1234", false)).ToString();
            };
        }
        public IConfigInfo GetConfig(string bucketName)
        {
            if (_serverConfig == null)
            {
                _serverConfig = new FileSystemConfig(_bootstrapPath);
            }
#pragma warning disable 612
            _configInfo = new ConfigInfo(_serverConfig, _clientConfig);
#pragma warning restore 612
            return _configInfo;
        }
 internal ClusterManager(ClientConfiguration clientConfig, IServerConfig serverConfig, HttpClient httpClient, IDataMapper mapper, string username, string password, ILoggerFactory loggerFactory)
 {
     _loggerFactory = loggerFactory;
     Log = _loggerFactory.CreateLogger<ClusterManager>();
     _clientConfig = clientConfig;
     _serverConfig = serverConfig;
     Mapper = mapper;
     HttpClient = httpClient;
     _password = password;
     _username = username;
 }
Example #29
0
        public void Initialize(IServerConfig config)
        {
            Config = config;
            BindInterface = config.BindInterface;
            Port = config.Port;

            Initialize();
            ProcessRequest += ProcessHttpRequest;

            _logger.Information("Getwork server listening on {0:l}:{1}", BindInterface, Port);
        }
Example #30
0
        /// <summary>
        /// Initializes the specified pool.
        /// </summary>
        /// <param name="config">The configuration.</param>
        public void Initialize(IServerConfig config)
        {
            Config = config;

            BindIP = config.BindInterface;
            Port = config.Port;

            ClientConnected += StratumServer_ClientConnected;
            ClientDisconnected += StratumServer_ClientDisconnected;
            DataReceived += StratumServer_DataReceived;
        }
Example #31
0
 internal virtual bool SetupWorkItemInstance(IManagedApp workItem, IServerConfig serverConfig)
 {
     return(workItem.Setup(this, serverConfig));
 }
Example #32
0
 void ITestSetup.Setup(IRootConfig rootConfig, IServerConfig serverConfig)
 {
     base.Setup(rootConfig, serverConfig, SocketServerFactory.Instance, null, new ConsoleLogFactory(), null);
 }
Example #33
0
 /// <summary>
 /// Initialize a provider from a config
 /// </summary>
 /// <param name="config">The config.</param>
 /// <returns></returns>
 public virtual bool Init(IAppServer <T> server, IServerConfig config)
 {
     this.AppServer = server;
     this.m_Config  = config;
     return(true);
 }
        internal MapPathBasedVirtualPathEnumerator(VirtualPath virtualPath, RequestedEntryType requestedEntryType)
        {
            if (virtualPath.IsRelative)
            {
                throw new ArgumentException(SR.GetString(SR.Invalid_app_VirtualPath), "virtualPath");
            }

            _virtualPath        = virtualPath;
            _requestedEntryType = requestedEntryType;

            string physicalPath;

            if (!ServerConfig.UseServerConfig)
            {
                // Use the hosting environment to map the virtual path
                physicalPath = _virtualPath.MapPathInternal();
            }
            else
            {
                IServerConfig serverConfig = ServerConfig.GetInstance();
                _serverConfig2 = serverConfig as IServerConfig2;

                // Use serverConfig to map the virtual path
                physicalPath = serverConfig.MapPath(null, _virtualPath);

                if (_requestedEntryType != RequestedEntryType.Files)
                {
                    // For MetabaseServerConfig, get the subdirs that are not in the application, and add them to the exclude list.
                    if (_serverConfig2 == null)
                    {
                        string [] virtualSubdirsNotInApp = serverConfig.GetVirtualSubdirs(_virtualPath, false);
                        if (virtualSubdirsNotInApp != null)
                        {
                            _exclude = new Hashtable(StringComparer.OrdinalIgnoreCase);
                            foreach (string subdir in virtualSubdirsNotInApp)
                            {
                                _exclude[subdir] = subdir;
                            }
                        }
                    }

                    // Get subdirs that are virtual directories, and record their physical mappings.
                    // Ignore the virtualPaths if we only need files, since it only contains directories
                    string [] virtualSubdirsInApp = serverConfig.GetVirtualSubdirs(_virtualPath, true);
                    if (virtualSubdirsInApp != null)
                    {
                        _virtualPaths = new Hashtable(StringComparer.OrdinalIgnoreCase);
                        foreach (string subdir in virtualSubdirsInApp)
                        {
                            VirtualPath subpath         = _virtualPath.SimpleCombineWithDir(subdir);
                            string      subPhysicalPath = serverConfig.MapPath(null, subpath);
                            if (FileUtil.DirectoryExists(subPhysicalPath))
                            {
                                _virtualPaths[subdir] = new MapPathBasedVirtualDirectory(subpath.VirtualPathString);
                            }
                        }

                        // Create enumerator for the virtual paths
                        _virtualEnumerator = _virtualPaths.Values.GetEnumerator();
                    }
                }
            }

            // Create an enumerator for the physical files and directories at this path
            _fileEnumerator = FileEnumerator.Create(physicalPath);

            // Reset the enumerator. Note that we don't support the Reset method.
            _useFileEnumerator = false;
        }
Example #35
0
 public override void OnInit(IServerConfig config)
 {
     EventService.AddEvent(ServiceEventDefine.ServiceEvent.GameFinsih, OnGameFinsih);
 }
Example #36
0
        /// <summary>
        /// Setups the appServer instance
        /// </summary>
        /// <param name="rootConfig">The root config.</param>
        /// <param name="config">The socket server instance config.</param>
        /// <param name="socketServerFactory">The socket server factory.</param>
        /// <param name="requestFilterFactory">The request filter factory.</param>
        /// <returns></returns>
        protected virtual bool Setup(IRootConfig rootConfig, IServerConfig config, ISocketServerFactory socketServerFactory, IRequestFilterFactory <TRequestInfo> requestFilterFactory)
        {
            if (rootConfig == null)
            {
                throw new ArgumentNullException("rootConfig");
            }

            RootConfig = rootConfig;

            if (!m_ThreadPoolConfigured)
            {
                if (!TheadPoolEx.ResetThreadPool(rootConfig.MaxWorkingThreads >= 0 ? rootConfig.MaxWorkingThreads : new Nullable <int>(),
                                                 rootConfig.MaxCompletionPortThreads >= 0 ? rootConfig.MaxCompletionPortThreads : new Nullable <int>(),
                                                 rootConfig.MinWorkingThreads >= 0 ? rootConfig.MinWorkingThreads : new Nullable <int>(),
                                                 rootConfig.MinCompletionPortThreads >= 0 ? rootConfig.MinCompletionPortThreads : new Nullable <int>()))
                {
                    return(false);
                }

                m_ThreadPoolConfigured = true;
            }

            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            if (!(config is ServerConfig))
            {
                //Use config plain model directly to avoid extra object casting in runtime
                var newConfig = new ServerConfig();
                config.CopyPropertiesTo(newConfig);
                config = newConfig;
            }

            Config = config;

            m_SocketServerFactory = socketServerFactory;

            SetupLogger();

            if (!SetupSecurity(config))
            {
                return(false);
            }

            if (!SetupListeners(config))
            {
                if (Logger.IsErrorEnabled)
                {
                    Logger.Error("Invalid config ip/port");
                }

                return(false);
            }

            if (!SetupRequestFilterFactory(config, requestFilterFactory))
            {
                return(false);
            }

            m_CommandLoaders = new List <ICommandLoader>
            {
                new ReflectCommandLoader()
            };

            if (Config.EnableDynamicCommand)
            {
                ICommandLoader dynamicCommandLoader;

                try
                {
                    dynamicCommandLoader = AssemblyUtil.CreateInstance <ICommandLoader>("SuperSocket.Dlr.DynamicCommandLoader, SuperSocket.Dlr");
                }
                catch (Exception e)
                {
                    if (Logger.IsErrorEnabled)
                    {
                        Logger.Error("The file SuperSocket.Dlr is required for dynamic command support!", e);
                    }

                    return(false);
                }

                m_CommandLoaders.Add(dynamicCommandLoader);
            }

            if (!SetupCommands(m_CommandDict))
            {
                return(false);
            }

            return(SetupSocketServer());
        }
Example #37
0
 protected override bool Setup(IRootConfig rootConfig, IServerConfig config)
 {
     return(base.Setup(rootConfig, config));
 }
Example #38
0
 /// <summary>
 /// Starts the HTTP streaming connection.
 /// </summary>
 /// <param name="username"></param>
 /// <param name="password"></param>
 void StartProvider(string username, string password)
 {
     _serverConfig = new HttpServerConfig(ClientConfig, username, password);
     _serverConfig.Initialize();
     Log.Debug("Starting provider on main thread: {0}", Thread.CurrentThread.ManagedThreadId);
 }
Example #39
0
 public ServerTimer(IServerConfig config, ChatServer server)
 {
     this.server = server;
     timer       = new Timer(TimerCallbackAction, null, config.TimerInterval, config.TimerInterval);
 }
Example #40
0
 protected abstract void OnConfigure(IServerConfig config);
Example #41
0
 public SocketListener(IServerConfig serverConfig)
 {
     config = serverConfig;
 }
        bool IDynamicBootstrap.AddAndStart(IServerConfig config)
        {
            var dynamicBootstrap = m_InnerBootstrap as IDynamicBootstrap;

            return(dynamicBootstrap.AddAndStart(config));
        }
        public static ITransactionItem Create <TResourceItemType, TDataType>(Action <TDataType> assignAction, IServerConfig config, Func <TDataType> accessFunc = null)
            where TResourceItemType : ServerResourceItem <TDataType>, ITransactionItem, IResourceCreator <TDataType>, new()
        {
            var resourceItem = new TResourceItemType();

            resourceItem.Assigner = assignAction;
            resourceItem.Accessor = accessFunc;
            TDataType resource = default(TDataType);

            try
            {
                resource = resourceItem.CreateResource(config);
            }
            catch (Exception e)
            {
                throw new Exception(string.Format("Failed to create the server resource '{0}'.", resourceItem.Name), e);
            }

            assignAction(resource);
            return(resourceItem);
        }
Example #44
0
        //Attach default receive buffer pool definition
        private List <IBufferPoolConfig> AttachReceiveBufferPool(IEnumerable <IBufferPoolConfig> bufferPools, IServerConfig config)
        {
            //The buffer expading trend: 1, 2, 4, 8, which is 15 totaly
            var initialCount = Math.Min(Math.Max(config.MaxConnectionNumber / 15, 100), config.MaxConnectionNumber);

            var bufferDefinitions = new List <IBufferPoolConfig>();

            IBufferPoolConfig preDefinedReceiveBufferPool = null;

            if (bufferPools != null && bufferPools.Any())
            {
                preDefinedReceiveBufferPool = bufferPools.FirstOrDefault(p => p.BufferSize == config.ReceiveBufferSize);
                bufferDefinitions.AddRange(bufferPools.Where(p => p != preDefinedReceiveBufferPool));
            }

            var finalInitialCount = initialCount;

            if (preDefinedReceiveBufferPool != null)
            {
                finalInitialCount += preDefinedReceiveBufferPool.InitialCount;
            }

            bufferDefinitions.Add(new BufferPoolConfig(config.ReceiveBufferSize, finalInitialCount));
            return(bufferDefinitions);
        }
 public bool Initialize(IServerConfig config)
 {
     m_Dict = new ConcurrentDictionary <string, TAppSession>(4 * Environment.ProcessorCount, config.MaxConnectionNumber, StringComparer.OrdinalIgnoreCase);
     return(true);
 }
Example #46
0
 //---------------------------------------------------------------------
 public bool Setup(IServerConfig serverConfig)
 {
     return(Setup(serverConfig, null,
                  new DefaultReceiveFilterFactory <SuperSocketReceiveFilter, BufferedPackageInfo <ushort> >(),
                  new SuperSocketLogFactory()));
 }
Example #47
0
 /// <summary>
 /// Setups the appServer instance
 /// </summary>
 /// <param name="rootConfig">The SuperSocket root config.</param>
 /// <param name="config">The socket server instance config.</param>
 /// <param name="socketServerFactory">The socket server factory.</param>
 /// <returns></returns>
 protected virtual bool Setup(IRootConfig rootConfig, IServerConfig config, ISocketServerFactory socketServerFactory)
 {
     return(Setup(rootConfig, config, socketServerFactory, null));
 }
Example #48
0
 internal ComServer(IServerConfig config)
     : base(config)
 {
 }
Example #49
0
        /// <summary>
        /// Setups the listeners base on server configuration
        /// </summary>
        /// <param name="config">The config.</param>
        /// <returns></returns>
        private bool SetupListeners(IServerConfig config)
        {
            var listeners = new List <ListenerInfo>();

            try
            {
                if (config.Port > 0)
                {
                    listeners.Add(new ListenerInfo
                    {
                        EndPoint = new IPEndPoint(ParseIPAddress(config.Ip), config.Port),
                        BackLog  = config.ListenBacklog,
                        Security = BasicSecurity
                    });
                }
                else
                {
                    if (!string.IsNullOrEmpty(config.Ip))
                    {
                        if (Logger.IsErrorEnabled)
                        {
                            Logger.Error("Ip is required in config!");
                        }

                        return(false);
                    }
                }

                //There are listener defined
                if (config.Listeners != null && config.Listeners.Any())
                {
                    //But ip and port were configured in server node
                    //We don't allow this case
                    if (listeners.Count > 0)
                    {
                        if (Logger.IsErrorEnabled)
                        {
                            Logger.Error("If you configured Ip and Port in server node, you cannot defined listeners any more!");
                        }

                        return(false);
                    }

                    foreach (var l in config.Listeners)
                    {
                        SslProtocols configProtocol;

                        if (string.IsNullOrEmpty(l.Security) && BasicSecurity != SslProtocols.None)
                        {
                            configProtocol = BasicSecurity;
                        }
                        else if (!l.Security.TryParseEnum <SslProtocols>(true, out configProtocol))
                        {
                            if (Logger.IsErrorEnabled)
                            {
                                Logger.ErrorFormat("Failed to parse '{0}' to SslProtocol!", config.Security);
                            }

                            return(false);
                        }

                        if (configProtocol != SslProtocols.None && (config.Certificate == null || !config.Certificate.IsEnabled))
                        {
                            if (Logger.IsErrorEnabled)
                            {
                                Logger.Error("There is no certificate defined and enabled!");
                            }
                            return(false);
                        }

                        listeners.Add(new ListenerInfo
                        {
                            EndPoint = new IPEndPoint(ParseIPAddress(l.Ip), l.Port),
                            BackLog  = l.Backlog,
                            Security = configProtocol
                        });
                    }
                }

                if (!listeners.Any())
                {
                    if (Logger.IsErrorEnabled)
                    {
                        Logger.Error("No listener defined!");
                    }
                }

                m_Listeners = listeners.ToArray();

                return(true);
            }
            catch (Exception e)
            {
                if (Logger.IsErrorEnabled)
                {
                    Logger.Error(e);
                }

                return(false);
            }
        }
 protected void InitSelf()
 {
     appCenter     = EasyInject.Get <AppCenter>();
     configManager = EasyInject.Get <IServerConfig>();
     P2PServer     = new P2PServer();
 }
Example #51
0
 /// <summary>
 /// Starts to listen
 /// </summary>
 /// <param name="config">The server config.</param>
 /// <returns></returns>
 public abstract bool Start(IServerConfig config);
Example #52
0
        public bool Setup(string serverType, string bootstrapUri, string assemblyImportRoot, IServerConfig config, string startupConfigFile)
        {
            m_AssemblyImporter = new AssemblyImport(assemblyImportRoot);

            if (!string.IsNullOrEmpty(startupConfigFile))
            {
                AppDomain.CurrentDomain.ResetConfiguration(startupConfigFile);
            }

            var serviceType = Type.GetType(serverType);

            m_AppServer = (IManagedApp)Activator.CreateInstance(serviceType);

            var bootstrap = (IBootstrap)Activator.GetObject(typeof(IBootstrap), bootstrapUri);

            var ret = m_AppServer.Setup(bootstrap, config);

            if (ret)
            {
                m_Log = ((IAppServer)m_AppServer).Logger;
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            }

            return(ret);
        }
Example #53
0
 public void Configure(IServerConfig config)
 {
     Name   = config.Name;
     Config = config;
     OnConfigure(config);
 }
Example #54
0
 public void ReportPotentialConfigChange(IServerConfig config)
 {
     m_ManagedApp.ReportPotentialConfigChange(config);
 }
Example #55
0
 public bool Setup(IBootstrap bootstrap, IServerConfig config, SocketBase.Provider.ProviderFactoryInfo[] factories)
 {
     throw new NotSupportedException();
 }
 public UdpSocketServerTest()
 {
     m_Config     = DefaultServerConfig;
     m_RootConfig = new RootConfig();
     m_Encoding   = new System.Text.UTF8Encoding();
 }
Example #57
0
 public void ReportPotentialConfigChange(IServerConfig config)
 {
     m_AppServer.ReportPotentialConfigChange(config);
 }
 protected override bool Setup(IRootConfig rootConfig, IServerConfig config)
 {
     Console.WriteLine("准备读取配置文件。。。。");
     Logger.Debug("准备读取配置文件。。。。");
     return(base.Setup(rootConfig, config));
 }
Example #59
0
 protected override bool Setup(IRootConfig rootConfig, IServerConfig config)
 {
     Console.WriteLine(TAG + "Setup");
     return(base.Setup(rootConfig, config));
 }
        /// <summary>
        /// Creates the socket server.
        /// </summary>
        /// <typeparam name="TPackageInfo">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 <TPackageInfo>(IAppServer appServer, ListenerInfo[] listeners, IServerConfig config)
            where TPackageInfo : IPackageInfo
        {
            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 <TPackageInfo>(appServer, listeners));

            default:
                throw new NotSupportedException("Unsupported SocketMode:" + config.Mode);
            }
        }