コード例 #1
0
        protected void EnsureDatabase(ServerProcess process)
        {
            var deviceSession = (SQLDeviceSession)Connect(process, process.ServerSession.SessionInfo);
            var database      = Database;

            Database = "postgres";             // This assumes all PostgreSQL installations have a postgres db.
            try
            {
                // Detect if the database exists
                bool      exists;
                SQLCursor cursor = deviceSession.Connection.Open(String.Format(CEnsureDatabase, database));
                try
                {
                    cursor.Next();
                    exists = (long)cursor[0] > 0;
                }
                finally
                {
                    cursor.Command.Connection.Close(cursor);
                }

                // If not, attempt to create it
                if (!exists)
                {
                    deviceSession.Connection.Execute(String.Format(CCreateDatabase, database));
                }
            }
            finally
            {
                Disconnect(deviceSession);
                Database = database;
            }
        }
コード例 #2
0
ファイル: Debugger.cs プロジェクト: laszlo-kiss/Dataphor
        private bool ShouldBreak(ServerProcess process, PlanNode node)
        {
            if (_disposed)
            {
                return(false);
            }

            if (process.ShouldBreak())
            {
                return(true);
            }

            if (_breakpoints.Count > 0)
            {
                DebugLocator currentLocation = process.ExecutingProgram.GetCurrentLocation();

                // Determine whether or not a breakpoint has been hit
                for (int index = 0; index < _breakpoints.Count; index++)
                {
                    Breakpoint breakpoint = _breakpoints[index];
                    if
                    (
                        (breakpoint.Locator == currentLocation.Locator) &&
                        (breakpoint.Line == currentLocation.Line) &&
                        ((breakpoint.LinePos == -1) || (breakpoint.LinePos == currentLocation.LinePos))
                    )
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
コード例 #3
0
ファイル: NativeMarshal.cs プロジェクト: laszlo-kiss/Dataphor
 public static TableVar NativeTableToTableVar(ServerProcess process, NativeTableValue nativeTable)
 {
     using (Plan plan = new Plan(process))
     {
         return(NativeTableToTableVar(plan, nativeTable));
     }
 }
コード例 #4
0
ファイル: SimpleDevice.cs プロジェクト: laszlo-kiss/Dataphor
 public void LoadTable(ServerProcess process, Schema.TableVar tableVar)
 {
     lock (_loadedTables)
     {
         if (!IsLoaded(tableVar))
         {
             _loadedTables.Add(tableVar);
             if (File.Exists(GetTableVarFileName(tableVar)))
             {
                 using (FileStream stream = new FileStream(GetTableVarFileName(tableVar), FileMode.Open, FileAccess.Read))
                 {
                     NativeTable nativeTable = Tables[tableVar];
                     while (stream.Position < stream.Length)
                     {
                         int    length   = StreamUtility.ReadInteger(stream);
                         byte[] rowValue = new byte[length];
                         stream.Read(rowValue, 0, rowValue.Length);
                         IRow row = (IRow)DataValue.FromPhysical(process.ValueManager, nativeTable.RowType, rowValue, 0);
                         try
                         {
                             nativeTable.Insert(process.ValueManager, row);
                         }
                         finally
                         {
                             row.Dispose();
                         }
                     }
                 }
             }
         }
     }
 }
コード例 #5
0
        protected void DetermineVersion(ServerProcess process)
        {
            var deviceSession = (SQLDeviceSession)Connect(process, process.ServerSession.SessionInfo);

            try
            {
                SQLCursor cursor = deviceSession.Connection.Open("SELECT version()");
                try
                {
                    string version = String.Empty;
                    cursor.Next();
                    var rawVersion = (string)cursor[0];
                    version = rawVersion.Split(' ')[1];

                    if (version.Length > 0)
                    {
                        _majorVersion = Convert.ToInt32(version.Substring(0, version.IndexOf('.')));
                    }
                }
                finally
                {
                    cursor.Command.Connection.Close(cursor);
                }
            }
            finally
            {
                Disconnect(deviceSession);
            }
        }
コード例 #6
0
ファイル: Plan.cs プロジェクト: laszlo-kiss/Dataphor
 public Plan(ServerProcess serverProcess) : base()
 {
     SetServerProcess(serverProcess);
     _symbols = new Symbols(_serverProcess.ServerSession.SessionInfo.DefaultMaxStackDepth, _serverProcess.ServerSession.SessionInfo.DefaultMaxCallDepth);
     PushSecurityContext(new SecurityContext(_serverProcess.ServerSession.User));
     PushStatementContext(new StatementContext(StatementType.Select));
 }
コード例 #7
0
        public static void End()
        {
            if (Message != null)
            {
                Message.End();
                Message = null;

                if (channel != null)
                {
                    ChannelServices.UnregisterChannel(channel);
                    channel = null;
                }
            }

            if (ServerProcess != null)
            {
                if (!ServerProcess.HasExited)
                {
                    ServerProcess.Kill();
                }

                ServerProcess.Dispose();
                ServerProcess = null;
            }
        }
コード例 #8
0
        public async Task StartServerById(string id, int maxRamMB, int minRamMB)
        {
            var server = await _repo.GetServerById(id);

            if (server == null)
            {
                // TODO: Add error handling here
                return;
            }
            if (_runningServers.ContainsKey(id))
            {
                // TODO: Add error handling here
                return;
            }

            var serverProcess = new ServerProcess(server.Id, maxRamMB, minRamMB);

            _runningServers.TryAdd(server.Id, serverProcess);
            var pId = serverProcess.StartServer(_logger, _angularHub);

            server.MaxRamMB  = maxRamMB;
            server.MinRamMB  = minRamMB;
            server.ProcessId = pId;
            server.IsRunning = true;
            server.TimesRan++;
            await _repo.UpsertServer(server);

            return;
        }
コード例 #9
0
        public override DataVar InternalExecute(ServerProcess AProcess, DataVar[] AArguments)
        {
            if (AProcess.ServerSession.Server.Catalog.Generators == null)             // if not set already
            {
                // check for existing table named Datphor.Generators
                Schema.TableVar LTableVar = (Schema.TableVar)Compiler.ResolveCatalogIdentifier(AProcess.Plan, "System.Generators", false);

                if (LTableVar == null)                 // if system.generators doesn't already exist
                {
                    // get device
                    Schema.Device LDevice =
                        AArguments.Length > 0
                                                        ? (Schema.Device)Compiler.ResolveCatalogIdentifier(AProcess.Plan, AArguments[0].Value.AsString, true)
                                                        : Language.D4.Compiler.GetDefaultDevice(AProcess.Plan, true);

                    // make sure the device is started so that DeviceScalarTypes is filled
                    AProcess.EnsureDeviceStarted(LDevice);

                    // create table type
                    Schema.TableType LTableType = new Schema.TableType();
                    // use System.String if available else System.IString
                    if (LDevice.DeviceScalarTypes.Contains(AProcess.Plan.Catalog.DataTypes.SystemIString))
                    {
                        LTableType.Columns.Add(new Schema.Column("ID", AProcess.Plan.Catalog.DataTypes.SystemIString));
                    }
                    else
                    {
                        LTableType.Columns.Add(new Schema.Column("ID", AProcess.Plan.Catalog.DataTypes.SystemString));
                    }
                    LTableType.Columns.Add(new Schema.Column("NextKey", AProcess.Plan.Catalog.DataTypes.SystemInteger));

                    // create table
                    LTableVar = new Schema.BaseTableVar("System.Generators", LTableType, LDevice);
                    MetaData LMetaData = new MetaData();
                    LMetaData.Tags.Add(new Tag("Storage.Length", "200", false, true));
                    LTableVar.Columns.Add(new Schema.TableVarColumn(LTableType.Columns["ID"], LMetaData));
                    LTableVar.Columns.Add(new Schema.TableVarColumn(LTableType.Columns["NextKey"]));
                    LTableVar.Keys.Add(new Schema.Key(new Schema.TableVarColumn[] { LTableVar.Columns["ID"] }));
                    LTableVar.Owner   = AProcess.Plan.User;
                    LTableVar.Library = AProcess.Plan.CurrentLibrary;
                    LTableVar.AddDependency(LDevice);
                    LTableVar.AddDependency((Schema.ScalarType)LTableVar.Columns[0].DataType);
                    LTableVar.AddDependency((Schema.ScalarType)LTableVar.Columns[1].DataType);

                    Compiler.Bind(AProcess.Plan, new CreateTableNode((Schema.BaseTableVar)LTableVar)).Execute(AProcess);

                    if (AProcess.Plan.User.ID == Server.Server.CAdminUserID)
                    {
                        Schema.Group LGroup = AProcess.Plan.Catalog.Groups[Server.Server.CUserGroupName];
                        LGroup.GrantRight(LTableVar.Rights.Select, true);
                        LGroup.GrantRight(LTableVar.Rights.Insert, true);
                        LGroup.GrantRight(LTableVar.Rights.Update, true);
                    }
                }

                // set generator table
                SystemSetGeneratorsNode.SetGenerator(AProcess, LTableVar);
            }
            return(null);
        }
コード例 #10
0
 private void ServerInfoTimer(object source, ElapsedEventArgs e)
 {
     if (ServerProcess.IsRunning())
     {
         try
         {
             ServerQuery query = new ServerQuery("127.0.0.1", 2303);
             Dispatcher.Invoke(() =>
             {
                 PlayerCount.Text = Convert.ToString(query.getPlayer());
             });
         }
         catch (Exception ex)
         {
             Debug.Write(ex.Message);
         }
     }
     else
     {
         Dispatcher.Invoke(() =>
         {
             PlayerCount.Text = "0";
         });
     }
 }
コード例 #11
0
        protected override SQLConnection InternalCreateConnection()
        {
            // ConnectionClass:
            //  ODBCConnection (default)
            // ConnectionStringBuilderClass
            // LinterADOConnectionStringBuilder (default)

            D4.ClassDefinition classDefinition =
                new D4.ClassDefinition
                (
                    Device.ConnectionClass == String.Empty ?
                    "ODBCConnection.ODBCConnection" :
                    Device.ConnectionClass
                );
            D4.ClassDefinition builderClass =
                new D4.ClassDefinition
                (
                    Device.ConnectionStringBuilderClass == String.Empty ?
                    "LinterDevice.LinterODBCConnectionStringBuilder" :
                    Device.ConnectionStringBuilderClass
                );
            ConnectionStringBuilder connectionStringBuilder = (ConnectionStringBuilder)ServerProcess.CreateObject(builderClass, new object[] {});

            D4.Tags tags = new D4.Tags();
            tags.AddOrUpdate("DataSource", Device.DataSource);
            tags.AddOrUpdate("UserName", DeviceSessionInfo.UserName);
            tags.AddOrUpdate("Password", DeviceSessionInfo.Password);

            tags = connectionStringBuilder.Map(tags);
            Device.GetConnectionParameters(tags, DeviceSessionInfo);
            string connectionString = SQLDevice.TagsToString(tags);

            return((SQLConnection)ServerProcess.CreateObject(classDefinition, new object[] { connectionString }));
        }
コード例 #12
0
        private string SaveDeviceSettings(ServerProcess process)
        {
            D4TextEmitter emitter = new D4TextEmitter();
            Block         block   = new Block();

            IServerProcess localProcess = (IServerProcess)process;
            IServerCursor  cursor       = localProcess.OpenCursor("select Devices { ID }", null);

            try
            {
                using (IRow row = cursor.Plan.RequestRow())
                {
                    while (cursor.Next())
                    {
                        cursor.Select(row);
                        Schema.Device device = process.CatalogDeviceSession.ResolveCatalogObject((int)row[0 /*"ID"*/]) as Schema.Device;
                        if ((device != null) && (device.ClassDefinition.Attributes.Count > 0))
                        {
                            block.Statements.Add(SaveSystemDeviceSettings(device));
                        }
                    }
                }
            }
            finally
            {
                localProcess.CloseCursor(cursor);
            }

            return(new D4TextEmitter().Emit(block) + "\r\n");
        }
コード例 #13
0
ファイル: TableBuffer.cs プロジェクト: laszlo-kiss/Dataphor
 public TableBuffer(ServerProcess AProcess, Schema.TableVar ATableVar) : base()
 {
     FTableVar = ATableVar;
     FFanout   = CDefaultClusteredFanout;
     FCapacity = CDefaultClusteredCapacity;
     InternalInitialize(AProcess);
 }
コード例 #14
0
        // StartProcess
        public IRemoteServerProcess StartProcess(ProcessInfo processInfo, out int processID)
        {
            ServerProcess serverProcess = (ServerProcess)_serverSession.StartProcess(processInfo);

            processID = serverProcess.ProcessID;
            return(new RemoteServerProcess(this, serverProcess));
        }
コード例 #15
0
        protected override void OnShown(EventArgs e)
        {
            var workerFactory = new WorkerManager(
                new BufferManager(10, 2048), TimeSpan.FromTicks(1), _logger);

            var listener = new Listener(
                new ListenerSettings(IPAddress.Any, 8088),
                s => workerFactory.Get(new WorkerSocket(s))
                );

            var process = new ServerProcess(
                listener, () => new HttpMessageHandler(_logger),
                _logger)
                {
                    Name = "sandbox",
                    Server = _server
                };

            process.Start();

            StartStopButton.Click += (s, ce) =>
                {
                    if (process.IsStarted)
                    {
                        process.Stop();
                        StartStopButton.Text = "Start";
                    }
                    else
                    {
                        process.Start();
                        StartStopButton.Text = "Stop";
                    }
                };
        }
コード例 #16
0
 /// <summary>
 /// Kill the server
 /// </summary>
 public static void KillServer()
 {
     if (ServerProcess != null && !ServerProcess.HasExited)
     {
         ServerProcess.Kill();
     }
 }
コード例 #17
0
ファイル: TableBuffer.cs プロジェクト: laszlo-kiss/Dataphor
 public TableBuffer(ServerProcess AProcess, Schema.TableVar ATableVar, int AFanout, int ACapacity)
 {
     FTableVar = ATableVar;
     FFanout   = AFanout;
     FCapacity = ACapacity;
     InternalInitialize(AProcess);
 }
コード例 #18
0
ファイル: TableBuffer.cs プロジェクト: laszlo-kiss/Dataphor
        public TableBufferIndex
        (
            ServerProcess AProcess,
            Schema.Order AKey,
            Schema.RowType AKeyRowType,
            Schema.RowType ADataRowType,
            bool AIsClustered,
            int AFanout,
            int ACapacity
        ) : base(AFanout, ACapacity, AKeyRowType.StaticByteSize, ADataRowType.StaticByteSize)
        {
            FKey = AKey;
                        #if DEBUG
            for (int LIndex = 0; LIndex < FKey.Columns.Count; LIndex++)
            {
                if (FKey.Columns[LIndex].Sort == null)
                {
                    throw new Exception("Sort is null");
                }
            }
                        #endif

            FKeyRowType  = AKeyRowType;
            FDataRowType = ADataRowType;
            FIsClustered = AIsClustered;
            Create(AProcess);
        }
コード例 #19
0
        /// <summary>
        ///     Stop the language server.
        /// </summary>
        /// <returns>
        ///     A <see cref="Task"/> representing the shutdown operation.
        /// </returns>
        public async Task Shutdown()
        {
            LspConnection connection = _connection;

            if (connection != null)
            {
                if (connection.IsOpen)
                {
                    connection.SendEmptyNotification("shutdown");
                    connection.SendEmptyNotification("exit");
                    connection.Disconnect(flushOutgoing: true);
                }

                await connection.HasHasDisconnected;
            }

            ServerProcess serverProcess = _process;

            if (serverProcess != null)
            {
                if (serverProcess.IsRunning)
                {
                    await serverProcess.Stop();
                }
            }

            IsInitialized    = false;
            _readyCompletion = new TaskCompletionSource <object>();
        }
コード例 #20
0
        /// <summary>
        /// Starts the process of listening for server connections.
        /// </summary>
        private void Start()
        {
            // 1. Set up processor for Ctrl-C and Ctrl-Break to end server.
            Console.CancelKeyPress += Console_CancelKeyPress;

            // 2. Create new server process instance and start it
            this.serverProcess = new ServerProcess();

            Console.WriteLine("Starting server game loop (press Ctrl-C to end) ...");
            this.serverProcess.Start();

            // 3. Set up listening socket to handle incoming client connections
            // If you're not familiar with socket programming, you may want to get a book. This is about as simple
            // an example as I can make.
            var endpoint = new IPEndPoint(IPAddress.Parse(Properties.Settings.Default.IPAddress), Properties.Settings.Default.IPPort);
            var socket   = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            socket.Bind(endpoint);
            socket.Listen(Properties.Settings.Default.MaxConnections);
            Console.WriteLine("Listening on {0}:{1} ...", Properties.Settings.Default.IPAddress, Properties.Settings.Default.IPPort);

            while (listenLoop)
            {
                done.Reset();
                socket.BeginAccept(new AsyncCallback(SocketAccept), socket);
                done.WaitOne();
            }

            Console.WriteLine("Shutting down ...");
            socket.Close();
            this.serverProcess.Stop();
            Console.WriteLine("Done.");
        }
コード例 #21
0
ファイル: Plan.cs プロジェクト: laszlo-kiss/Dataphor
        public void BindToProcess(ServerProcess process)
        {
            PopSecurityContext();
            PushSecurityContext(new SecurityContext(process.ServerSession.User));

            SetServerProcess(process);
        }
コード例 #22
0
ファイル: ServerScript.cs プロジェクト: laszlo-kiss/Dataphor
        internal ServerScript(ServerProcess process, string script, DebugLocator locator) : base()
        {
            _process       = process;
            _batches       = new ServerBatches();
            _messages      = new ParserMessages();
            _sourceContext = new SourceContext(script, locator);
            try
            {
                _script = _process.ParseScript(script, _messages);
            }
            catch (SyntaxException e)
            {
                e.SetLocator(locator);
                throw;
            }
            _messages.SetLocator(locator);
            if ((_script is Block) && (((Block)_script).Statements.Count > 0))
            {
                Block block = (Block)_script;

                for (int index = 0; index < block.Statements.Count; index++)
                {
                    _batches.Add(new ServerBatch(this, block.Statements[index]));
                }
            }
            else
            {
                _batches.Add(new ServerBatch(this, _script));
            }
        }
コード例 #23
0
 private void DisposeCachedPlans(ServerProcess process, CachedPlans plans)
 {
     foreach (ServerPlan plan in plans)
     {
         DisposeCachedPlan(process, plan);
     }
 }
コード例 #24
0
        /// <summary>Adds the given plan to the plan cache.</summary>
        /// <remarks>
        /// The plan is not contained within the cache after this call, it is assumed in use by the client.
        /// This call simply reserves storage and marks the plan as referenced for the LRU.
        /// </remarks>
        public void Add(ServerProcess process, string statement, int contextHashCode, ServerPlan plan)
        {
            CachedPlans      bumped = null;
            CachedPlanHeader header = GetPlanHeader(process, statement, contextHashCode);

            plan.Header             = header;
            plan.PlanCacheTimeStamp = process.Catalog.PlanCacheTimeStamp;

            lock (this)
            {
                if (_plans != null)
                {
                    CachedPlans plans;
                    if (!_plans.TryGetValue(header, out plans))
                    {
                        plans = new CachedPlans();
                    }
                    bumped = _plans.Reference(header, plans);
                }
            }

            if (bumped != null)
            {
                DisposeCachedPlans(process, bumped);
            }
        }
コード例 #25
0
        public void CrashWithDialog(string caption, string text)
        {
            _crashWithDialog = true;
            int k = 0;

            while (!ServerStatus.Status && k < 40)
            {
                Thread.Sleep(50);
                k++;
            }
            if (!(this is ValveHltvServer) && ServerStatus.Map.Length > 0)
            {
                _logger.Warn(string.Format(Properties.Resources.log_ServerCrashedWithDialogOnMap.Replace("\\n", "\n"), Options.HostName, ServerStatus.Map, ConsoleText.Trim(), caption, text));
            }
            else
            {
                _logger.Warn(string.Format(Properties.Resources.log_ServerCrashedWithDialog.Replace("\\n", "\n"), Options.HostName, ConsoleText.Trim(), caption, text));
            }
            //while (_serverThread.ThreadState != System.Threading.ThreadState.WaitSleepJoin && k < 40)
            //{
            //    Thread.Sleep(50);
            //    k++;
            //}
            try
            {
                ServerProcess.Kill();
            }
            catch (Exception e)
            {
                _logger.DebugException(Properties.Resources.log_ProcessAlreadyKilled, e);
            }
            Thread.Sleep(100);
        }
コード例 #26
0
 protected internal ServerPlan(ServerProcess process) : base()
 {
     _process = process;
     _plan    = new Plan(process);
     _program = new Program(process, _iD);
     _program.ShouldPushLocals = true;
 }
コード例 #27
0
        private void RefreshServerData()
        {
            long memory     = 0;
            long memoryMax  = 0;
            long storage    = 0;
            long storageMax = 0;

            try
            {
                ServerProcess?.Refresh();
                memory    = ServerProcess?.PrivateMemorySize64 ?? 0;
                memoryMax = ServerProcess?.VirtualMemorySize64 ?? 0;
                DriveInfo driveInfo = new DriveInfo(Directory.GetDirectoryRoot(Path.GetDirectoryName(Runner.MinecraftServerFolder)));
                storage    = driveInfo.TotalSize - driveInfo.TotalFreeSpace;
                storageMax = driveInfo.TotalSize;
            }
            catch (Exception e)
            {
                Console.Write(string.Format("Hit Exception during RefreshServerData = {0}", e));
            }

            Data.Memory     = memory;
            Data.MemoryMax  = memoryMax;
            Data.Storage    = storage;
            Data.StorageMax = storageMax;
        }
コード例 #28
0
ファイル: Index.cs プロジェクト: laszlo-kiss/Dataphor
 // Existing stream IndexNode constructor
 public IndexNode(ServerProcess AProcess, Index AIndex, StreamID AStreamID)
 {
     FProcess  = AProcess;
     FIndex    = AIndex;
     FStreamID = AStreamID;
     FStream   = FProcess.StreamManager.Open(AStreamID, LockMode.Shared);
     InternalInitialize();
 }
コード例 #29
0
 protected internal MemoryDeviceSession
 (
     Schema.Device device,
     ServerProcess serverProcess,
     Schema.DeviceSessionInfo deviceSessionInfo
 ) : base(device, serverProcess, deviceSessionInfo)
 {
 }
コード例 #30
0
 public ConsoleViewModel()
 {
     serverProcess = new ServerProcess();
     //serverProcess.OnConsoleNotifyOut += InstallProcess_OnConsoleNotifyOut;
     serverProcess.OnConsoleOut      += InstallProcess_OnConsoleOut;
     serverProcess.OnConsoleErrorOut += InstallProcess_OnConsoleOut;
     serverProcess.StartProcess();
 }
コード例 #31
0
 public async Task Close()
 {
     try
     {
         ServerProcess.Kill();
     }
     catch { }
 }
コード例 #32
0
        public void add_process_sets_server()
        {
            using (var server = GetServer())
            {
                var process = new ServerProcess(GetListener(), GetHandler, null);
                server.Add(process);

                Assert.Equal(server, process.Server);
            }
        }
コード例 #33
0
        public void remove_process_sets_server_to_null()
        {
            using (var server = GetServer())
            {
                var process = new ServerProcess(GetListener(), GetHandler, null);
                server.Add(process);

                server.Remove(process);
                Assert.Null(process.Server);
            }
        }
コード例 #34
0
        public void cannot_start_one_already_started()
        {
            using (var sut = new ServerProcess(
                GetListenerMock().Object, () => GetMessageHandlerMock().Object, null))
            {
                sut.Start();

                // ReSharper disable AccessToDisposedClosure
                // executed right away, not disposed at this point
                Assert.Throws<InvalidOperationException>(() => sut.Start());
                // ReSharper restore AccessToDisposedClosure

                Thread.Sleep(50);
            }
        }
コード例 #35
0
        public void dispose_removes_from_server()
        {
            var sut = new ServerProcess(
                GetListenerMock().Object, () => GetMessageHandlerMock().Object, null);

            var serverMock = new Mock<IServer>();
            serverMock.Setup(o => o.Remove(It.IsAny<ServerProcess>())).Verifiable();

            sut.Server = serverMock.Object;

            sut.Dispose();

            serverMock.Verify();

            GC.Collect();
        }
コード例 #36
0
        public void can_restart_a_process()
        {
            using (var sut = new ServerProcess(
                GetListenerMock().Object, () => GetMessageHandlerMock().Object, null))
            {
                sut.Start();
                Assert.True(sut.IsStarted);

                sut.Stop();
                Assert.False(sut.IsStarted);

                sut.Start();
                Assert.True(sut.IsStarted);

                Thread.Sleep(50);
            }
        }
コード例 #37
0
        public void disposed_process_is_removed()
        {
            using (var server = GetServer())
            {
                server.Add(new ServerProcess(GetListener(), GetHandler, null));

                var process = new ServerProcess(GetListener(), GetHandler, null);
                server.Add(process);

                Assert.Equal(2, server.Processes.Count());

                process.Dispose();

                Assert.Equal(1, server.Processes.Count());
                Assert.DoesNotContain(process, server.Processes);
            }
        }
コード例 #38
0
ファイル: RoomServer.cs プロジェクト: 247321453/YgoServer
 public bool Start()
 {
     if (IsListening) return true;
     IsListening = true;
     Config.Load();
     //本地api
     InitDeulListener();
     try
     {
         m_apilistener.Start();
     }
     catch (Exception e)
     {
         Logger.Error(e);
     }
     if (Config.Ports != null)
     {
         foreach (int port in Config.Ports)
         {
             ServerProcess server = new ServerProcess(port, Config.ApiPort, Config.ServerExe, Config.Config);
             server.Start();
             Porcess.Add(server);
         }
     }
     else {
         Logger.Error("no configs");
     }
     InitRoomListener();
     try
     {
         m_listener.Start();
     }
     catch (Exception e)
     {
         Logger.Error(e);
         Stop();
     }
     if (IsListening)
     {
         infoTimer.Start();
     }
     return IsListening;
 }
コード例 #39
0
        public void on_error_IsStarted_is_false()
        {
            var listenerMock = GetListenerMock();
            listenerMock
                .Setup(o => o.AcceptAsync())
                .Callback(() => { throw new Exception(); });

            using (var sut = new ServerProcess(
                listenerMock.Object, () => GetMessageHandlerMock().Object, null))
            {
                sut.Start();
                Thread.Sleep(50);

                Assert.False(sut.IsStarted);
            }
        }
コード例 #40
0
        public void on_error_Exception_is_set()
        {
            var exception = new Exception();

            var listenerMock = new Mock<IListener>();
            listenerMock
                .Setup(o => o.AcceptAsync())
                .Callback(() => { throw exception; });

            using (var sut = new ServerProcess(
                listenerMock.Object, () => GetMessageHandlerMock().Object, null))
            {
                sut.Start();
                Thread.Sleep(50);

                Assert.Equal(exception, sut.Exception);
            }
        }
コード例 #41
0
 public void start_with_no_server()
 {
     using (var sut = new ServerProcess(
         GetListenerMock().Object, () => GetMessageHandlerMock().Object, null))
     {
         // ReSharper disable AccessToDisposedClosure
         // executed right away, not disposed at this point
         Assert.DoesNotThrow(() => sut.Start());
         // ReSharper restore AccessToDisposedClosure
     }
 }