示例#1
0
        public override void Start()
        {
            try
            {
                if (Listener?.Running == true)
                {
                    return;
                }

                bool ret = connected ? true : Connect(ConnectTimeout);

                if (ret)
                {
                    Listener = new TcpListener(this);
                    Listener.Start();
                }

                if (Listener?.Running == true)
                {
                    OnStarted?.Invoke(new NetClientEventArgs <ITcpConnection>(this));
                }
            }
            catch (Exception ex)
            {
                OnException?.Invoke(new NetClientEventArgs <ITcpConnection>(this)
                {
                    Exception = ex
                });

                if (!connected)
                {
                    throw ex;
                }
            }
        }
示例#2
0
        public void Start()
        {
            clientList = new List <TcpClient>();

            listener = new TcpListener(ipEndPoint);
            listener.Start();

            alive = true;

            runner = new Thread(new ThreadStart(Run));
            runner.IsBackground = true;
            runner.Name         = "Tcp Listener Runner";
            runner.Start();
            while (!runner.IsAlive)
            {
                Thread.Sleep(10);
            }

            acceptor = new Thread(new ThreadStart(Accept));
            acceptor.IsBackground = true;
            acceptor.Name         = "Tcp Listener Acceptor";
            acceptor.Start();
            while (!acceptor.IsAlive)
            {
                Thread.Sleep(10);
            }

            if (OnStarted != null)
            {
                OnStarted.Invoke();
            }
        }
示例#3
0
        public void SwitchState()
        {
            State next = State.idle;

            switch (_State)
            {
            case State.idle:
                next       = State.started;
                _StartedAt = DateTime.Now;
                OnStarted?.Invoke();
                break;

            case State.paused:
                next       = State.started;
                _PauseSum += DateTime.Now - _PausedAt;
                _PausedAt  = new DateTime();
                OnStarted?.Invoke();
                break;

            case State.started:
                next      = State.paused;
                _PausedAt = DateTime.Now;
                OnPaused?.Invoke();
                break;
            }

            _State = next;
        }
示例#4
0
        internal override void InvokeEvent(ServerType type, IConnection conn, IMessage msg)
        {
            switch (type)
            {
            case ServerType.Started:
                OnStarted?.Invoke(conn, msg);
                break;

            case ServerType.Accepted:
                OnAccepted?.Invoke(conn, msg);
                break;

            case ServerType.Sended:
                OnSended?.Invoke(conn, msg);
                break;

            case ServerType.Received:
                OnRecieved?.Invoke(conn, msg);
                break;

            case ServerType.Disconnected:
                OnDisconnected?.Invoke(conn, msg);
                break;

            case ServerType.Stopped:
                OnStopped?.Invoke(conn, msg);
                break;
            }
        }
示例#5
0
        /// <summary>
        /// Run code in a new worker thread. WorkerDelegate should return true to end, false to repeat.
        /// </summary>
        /// <param name="worker">Delegate to be run</param>
        /// <param name="waitTime"></param>
        public static void Start(Func <bool> worker, int waitTime = 25)
        {
            if (IsRunning)
            {
                return;
            }

            WaitTime = waitTime;

            var frame  = new StackFrame(1);
            var method = frame.GetMethod();
            var type   = method.DeclaringType;
            var ns     = type != null ? type.Namespace : string.Empty;

            _worker = worker;
            _thread = new Thread(SafeWorkerDelegate)
            {
                Name         = $"Worker: {ns}.{type}",
                IsBackground = true,
                Priority     = ThreadPriority.BelowNormal,
            };

            Core.Logger.Debug("Starting {0} Thread Id={1}", _thread.Name, _thread.ManagedThreadId);

            _working = true;
            _thread.Start();

            OnStarted.Invoke();
        }
示例#6
0
        /// <summary>
        /// Run code in a new worker thread. WorkerDelegate should return true to end, false to repeat.
        /// </summary>
        /// <param name="worker">Delegate to be run</param>
        public void Start(WorkerDelegate worker)
        {
            if (IsRunning)
            {
                return;
            }

            var frame  = new StackFrame(1);
            var method = frame.GetMethod();
            var type   = method.DeclaringType;
            var ns     = type != null ? type.Namespace : string.Empty;

            _worker = worker;
            _thread = new Thread(SafeWorkerDelegate)
            {
                Name         = string.Format("Worker: {0}.{1}", ns, type),
                IsBackground = true,
                Priority     = ThreadPriority.BelowNormal,
            };

            Logger.Debug("Starting {0} Thread Id={1}", _thread.Name, _thread.ManagedThreadId);

            _working = true;
            _thread.Start();

            OnStarted.Invoke();
        }
示例#7
0
        public void Start(IPAddress address, int port)
        {
            if (IsClosing || IsWorking)
            {
                throw new InvalidOperationException("Listener must be closed before executing Start method.");
            }
            if (address is null || port == 0)
            {
                throw new ArgumentNullException();
            }

            OnStarting?.Invoke(this, new ListenerEventArgs {
                Server = this, UtcTime = DateTime.UtcNow
            });

            // IP Check
            if (
                NetworkInterface
                .GetAllNetworkInterfaces()
                .Where(interf =>
                       interf.OperationalStatus == OperationalStatus.Up)
                .Select(interf => new
            {
                uni = interf.GetIPProperties().UnicastAddresses,
                multi = interf.GetIPProperties().MulticastAddresses
            })
                .Where(item =>
                       item.uni.Where(ip => ip.Address == address).Count() > 0 ||
                       item.multi.Where(ip => ip.Address == address).Count() > 0
                       )
                .Count() == 0
                )
            {
                throw new ArgumentException("This IP address isn't assigned to active interface");
            }

            IPEndPoint endpoint = new IPEndPoint(address, port);

            this.socket = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            this.socket.Bind(endpoint);
            this.socket.Listen(50);

            CurrentPassword = GeneratePassword();

            OnStarted.Invoke(
                this,
                new ListenerEventArgs {
                Server = this, UtcTime = DateTime.UtcNow
            }
                );

            new Thread(() =>
            {
                while (!IsClosing)
                {
                    socket.BeginAccept(new AsyncCallback(AcceptCallback), socket);
                }
            });
        }
示例#8
0
        /////////////////////////////////////
        //          Public
        /////////////////////////////////////

        public bool Start(int port = 7788)
        {
            try
            {
                Host = new SimpleTcpServer();
                //Host.Delimiter
                //Host.DelimiterDataReceived += (o, e) => { Console.WriteLine("Delimter data received"); };
                //Host.DataReceived += (o, e) => { Console.WriteLine("##############Data received"); };
                //Host.DataReceived += DataReceived;
                Host.DelimiterDataReceived += DataReceived;

                Host.ClientConnected += ClientConnected;

                Host.Start(port);

                disconnectPing.Start();
                InvokeOutput("Server Started.");

                if (!hasConnectedBefore)
                {
                    hasConnectedBefore = true;
                    Application.Current.MainWindow.Closed += Program_Exit;
                }
                OnStarted?.Invoke();


                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Warning#001 :" + ex.Message);
                InvokeOutput("Server Not Started.");
                return(false);
            }
        }
示例#9
0
 public void StartListening(string ip, string port)
 {
     _webSocketServer = new WebSocketServer($"ws://{ip}:{port}");
     AddWsServerService();
     _webSocketServer.Start();
     OnStarted?.Invoke(this, EventArgs.Empty);
 }
示例#10
0
        async void ToggleAnimation()
        {
            if (IsRunning)
            {
                if (OnStartedAnimation != null)
                {
                    await OnStartedAnimation.Begin();
                }

                ToggleIndicator(IsRunning);

                OnStarted?.Invoke(this, null);
            }
            else
            {
                if (OnCompletedAnimation != null)
                {
                    await OnCompletedAnimation.Begin();
                }

                ToggleIndicator(IsRunning);

                OnCompleted?.Invoke(this, null);
            }

            void ToggleIndicator(bool isRunning)
            {
                IsVisible =
                    _loadingIndicator.IsVisible     =
                        _loadingIndicator.IsRunning =
                            IsRunning;

                Opacity = 1;
            }
        }
示例#11
0
 public IGraphPath FindPath()
 {
     OnStarted?.Invoke(this, new AlgorithmEventArgs());
     OnVertexVisited?.Invoke(this, new AlgorithmEventArgs());
     OnVertexEnqueued?.Invoke(this, new AlgorithmEventArgs());
     OnFinished?.Invoke(this, new AlgorithmEventArgs());
     return(new NullGraphPath());
 }
 private void MessagingStartedHandle(MessagingStartedData value)
 {
     synchronization.Post(async state =>
     {
         var connection = await CreateConnectionAsync(myId, value.SecurityKey);
         OnStarted?.Invoke(this, new StartMessagingConnectionEventArgs(connection, value.UserId));
     }, value);
 }
示例#13
0
        private async Task Start()
        {
            CurrentPhase = Phase.Running;
            if (_users.Count <= 1)
            {
                foreach (var user in _users)
                {
                    if (user.Bet > 0)
                    {
                        await _currency.AddAsync(user.UserId, "Race refund", user.Bet).ConfigureAwait(false);
                    }
                }

                var _sf = OnStartingFailed?.Invoke(this);
                CurrentPhase = Phase.Ended;
                return;
            }

            var _  = OnStarted?.Invoke(this);
            var _t = Task.Run(async() =>
            {
                var rng = new NadekoRandom();
                while (!_users.All(x => x.Progress >= 60))
                {
                    foreach (var user in _users)
                    {
                        user.Progress += rng.Next(1, 11);
                        if (user.Progress >= 60)
                        {
                            user.Progress = 60;
                        }
                    }

                    var finished = _users.Where(x => x.Progress >= 60 && !FinishedUsers.Contains(x))
                                   .Shuffle();

                    FinishedUsers.AddRange(finished);

                    var _ignore = OnStateUpdate?.Invoke(this);
                    await Task.Delay(2500).ConfigureAwait(false);
                }

                var win_amount = 0;

                foreach (var u in FinishedUsers)
                {
                    win_amount += (int)u.Bet;
                }

                if (FinishedUsers[0].Bet > 0)
                {
                    await _currency.AddAsync(FinishedUsers[0].UserId, "Won a Race", win_amount)
                    .ConfigureAwait(false);
                }

                var _ended = OnEnded?.Invoke(this);
            });
        }
        public static async void Start(IConfigurationRoot configuration, IServiceProvider services)
        {
            SystemController.configuration = configuration;
            SystemController.services      = services;

            if (Boolean.Parse(configuration["FirstRun"]))
            {
                if (!firstRun)
                {
                    firstRun = true;
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine("\nWelcome to MyNodes.NET. \nPlease configure the system in the web interface.\n");
                    Console.ForegroundColor = ConsoleColor.Gray;
                }

                return;
            }

            if (systemControllerStarted)
            {
                return;
            }
            systemControllerStarted = true;



            //read settings
            ReadConfig();


            await Task.Run(() =>
            {
                //waiting for starting web server
                Thread.Sleep(500);

                logs.AddSystemInfo("---------------- STARTING ------------------");

                if (nodesDb == null)
                {
                    ConnectToDB();
                }

                if (gateway == null)
                {
                    ConnectToGateway();
                }

                if (nodesEngine == null)
                {
                    StartNodesEngine();
                }

                logs.AddSystemInfo("------------- SARTUP COMPLETE --------------");

                OnStarted?.Invoke();
            });
        }
示例#15
0
        void StartSystem()
        {
            for (int i = 0; i < _systems.Count; ++i)
            {
                _systems[i].StartSystem(this);
            }

            OnStarted?.Invoke();
        }
 private void MessagingStartingHandle(MessagingStartingData value)
 {
     synchronization.Post(async state =>
     {
         var securityKey = GenerateSecurityKey();
         var connection  = await CreateConnectionAsync(myId, securityKey);
         await roomConnection.StartMessagingAsync(value.UserId, securityKey);
         OnStarted?.Invoke(this, new StartMessagingConnectionEventArgs(connection, value.UserId));
     }, value);
 }
示例#17
0
 /// <summary>
 /// Setup and run the story using the parents cancellationTokenSource & refreshRate
 /// </summary>
 /// <returns></returns>
 public void Start(CancellationTokenSource cancellationTokenSource, RefreshRate refreshRate)
 {
     RefreshRate             = refreshRate;
     StepCount               = (int)Duration.TotalMilliseconds / (int)RefreshRate;
     CancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationTokenSource.Token);
     Setup();
     State = StoryState.Running;
     OnStarted?.Invoke(this, EventArgs.Empty);
     Begin();
 }
示例#18
0
        public void Start(int bot)
        {
            if (!_run)
            {
                if (_wordlist == null)
                {
                    throw new Exception("Wordlist is null.");
                }
                if (!_wordlist.HasNext)
                {
                    throw new Exception("Wordlist is null.");
                }

                _theEnd = false;
                _run    = true;

                _threadList.Clear();

                _bot = bot;
                if (_bot > _wordlist.Count - _position)
                {
                    _bot = _wordlist.Count - _position;
                }

                _runnerStatus = RunnerStatus.Started;
                try { OnStarted?.Invoke(this, new StartEventArgs()
                    {
                        Bot = _bot
                    }); } catch (Exception ex) { OnException?.Invoke(this, new ExceptionEventArgs()
                    {
                        Location = "OnStarted", Exception = ex, Log = _log
                    }); }

                _stopwatch.Restart();
                _stopwatch.Start();

                _cts = new CancellationTokenSource();

                for (int i = 0; i < _bot; i++)
                {
                    int    num    = i;
                    Thread thread = new Thread(() => { Config(num, _cts.Token); })
                    {
                        IsBackground = true, Name = $"ID{num}"
                    };
                    thread.Start();
                    _threadList.Add(thread);
                }

                new Thread(() => { CompletedTask(); })
                {
                    IsBackground = true
                }.Start();
            }
        }
示例#19
0
        public void Start()
        {
            if (Math.Abs(Interval) < 0.001)
            {
                return;
            }

            OnStarted?.Invoke(this, new GameTimerEventArgs(TotalSeconds, Interval));
            IsStopped = false;
            IsStarted = true;
        }
示例#20
0
        public PanoDownloader()
        {
            m_UserDownloader   = new UserPanoDownloader();
            m_GoogleDownloader = new GooglePanoDownloader();

            m_UserDownloader.OnStarted += () => OnStarted?.Invoke();
            m_UserDownloader.OnLoaded  += tex => OnLoaded?.Invoke(tex);
            m_UserDownloader.OnFailed  += exception => OnFailed?.Invoke(exception);

            m_GoogleDownloader.OnStarted += () => OnStarted?.Invoke();
            m_GoogleDownloader.OnLoaded  += tex => OnLoaded?.Invoke(tex);
            m_GoogleDownloader.OnFailed  += exception => OnFailed?.Invoke(exception);
        }
示例#21
0
        public void Start()
        {
            if (Status != WorkerStatus.Stopped)
            {
                throw new InvalidOperationException("Worker must be stopped in order to start it");
            }

            Status = WorkerStatus.Starting;

            _cancellationTokenSource = new CancellationTokenSource();
            _worker = _workerWrapper(_cancellationTokenSource.Token);

            OnStarted?.Invoke(this, new EventArgs());
        }
示例#22
0
        /// <summary>
        /// IRC event: authenticated was OK, and we received a welcome message from the server.
        /// </summary>
        private void Client_Registered(object sender, EventArgs e)
        {
            TmiLog.Log("Authed on Twitch IRC server.");

            if (Status == ClientStatus.Connecting)
            {
                Status = ClientStatus.Started;
            }

            if (OnStarted != null)
            {
                OnStarted.Invoke(this, new EventArgs());
            }
        }
示例#23
0
            protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
            {
                var length = m_Bytes.Length;

                return(Task.Run(() =>
                {
                    OnStarted?.Invoke();
                    for (var i = 0; i < length; i += k_ChunkSize)
                    {
                        var count = Math.Min(k_ChunkSize, length - i);
                        stream.Write(m_Bytes, i, count);
                        OnProgress?.Invoke(i + count);
                    }
                }));
            }
示例#24
0
        /// <summary>
        /// Initialize and start objective
        /// </summary>
        public virtual void start()
        {
            Tools.log("Start " + getName());

            if (this.inProgress)
            {
                return;
            }

            elapsedTime = 0;

            this.play();

            OnStarted?.Invoke(this);
        }
        private void ThriftRpcProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            Process process = (Process)sender;

            ThriftRpcLog.Info($"RpcAgent({process.Id}): {e.Data}");
            OnMessage?.Invoke(process, e.Data);
            const string startString = "Starting the rpc server on";

            if (e.Data != null && e.Data.Contains(startString))
            {
                Log.InfoFormat("Found magic string \"{0}\" indicating that RPC Agent {1} has started successfully",
                               startString, process.Id);
                OnStarted?.Invoke(this, EventArgs.Empty);
            }
        }
示例#26
0
        public bool Start(DateTimeOffset lastKnownEvent = default(DateTimeOffset))
        {
            if (!ScheduledTask.IsScheduleRunning)
            {
                ScheduledTask.StartSchedule(lastKnownEvent);

                OnStarted?.Invoke(this, new WorkerStartedEventArgs());

                Store($"{Name} has started at {DateTime.Now}");

                return(true);
            }

            return(false);
        }
示例#27
0
        private bool ConnectInternal()
        {
            try
            {
                if (Listener?.Running == true)
                {
                    return(true);
                }

                bool ret = connected ? true : Connect(ConnectTimeout);

                if (ret)
                {
                    tryConnectCounter = 0;
                    Listener          = new TcpListener(this);
                    Listener.Start();
                }

                if (Listener?.Running == true)
                {
                    OnStarted?.Invoke(new NetClientEventArgs <ITcpConnection>(this));
                }

                if (ret)
                {
                    if (!started)
                    {
                        started = true;
                    }
                    return(true);
                }
            }
            catch (Exception ex)
            {
                OnException?.Invoke(new NetClientEventArgs <ITcpConnection>(this)
                {
                    Exception = ex
                });

                if (!connected && !created && !connecting)
                {
                    throw ex;
                }
                //if (!started && !connected && ReconnectEnable && created) Reconnect();
            }

            return(false);
        }
示例#28
0
        /// <summary>
        /// Start the TCPServer thread
        /// </summary>
        public void Start(UInt32 MaxClientConnections)
        {
            if (_IsRunning)
            {
                return;
            }

            if (MaxClientConnections != __DefaultMaxClientConnections)
            {
                _MaxClientConnections = MaxClientConnections;
            }

            try
            {
                Debug.WriteLine("[" + DateTime.Now + "] Starting TCP listener on port " + _Port);

                _TCPListener.Start((Int32)_MaxClientConnections);
            }
            catch (Exception e)
            {
                Debug.WriteLine("[" + DateTime.Now + "] An exception occured in Hermod.TCPServer.Start(MaxClientConnections) [_TCPListener.Start((Int32) _MaxClientConnections)]: " + e.Message + Environment.NewLine + e.StackTrace);
            }

            try
            {
                if (_ListenerThread == null)
                {
                    Debug.WriteLine("[" + DateTime.Now + "] An exception occured in Hermod.TCPServer.Start(MaxClientConnections) [_ListenerThread == null]!");
                }

                // Start the TCPListenerThread
                _ListenerThread.Start();
            }
            catch (Exception e)
            {
                Debug.WriteLine("[" + DateTime.Now + "] An exception occured in Hermod.TCPServer.Start(MaxClientConnections) [_ListenerThread.Start()]: " + e.Message + Environment.NewLine + e.StackTrace);
            }


            // Wait until socket has opened
            while (!_IsRunning)
            {
                Thread.Sleep(10);
            }

            OnStarted?.Invoke(this, DateTime.Now);
        }
示例#29
0
        public async Task Start(bool UseExamples, string ProfileNameSetting, string LicenseKeySetting)
        {
            configuration = new Oridashi.Fhir.Host.Configuration()
            {
                ProfileName = ProfileNameSetting,
                LicenseKey  = LicenseKeySetting,
                Mode        = Oridashi.Fhir.Host.Configuration.SelectSystem.AUTO,
                IsLive      = !UseExamples,
            };

            host = new Oridashi.Fhir.Host.FhirHost();
            await Task <Oridashi.Fhir.Host.Configuration> .Run(new Action(() => {
                configuration = host.Start(configuration);
                running = true;
                OnStarted?.Invoke();
            }));
        }
示例#30
0
 private void AtmptStart()
 {
     if (List_PendingToStart.Count > 0 && Vacancy > 0)
     {
         var load = List_PendingToStart.First();
         Log("Start", load);
         if (DebugMode)
         {
             Debug.WriteLine("{0}:\t{1}\tStart\t{2}", ClockTime, this, load);
         }
         List_PendingToStart.RemoveAt(0);
         HSet_Serving.Add(load);
         HC_Serving.ObserveChange(1, ClockTime);
         OnStarted.Invoke(load);
         Schedule(() => ReadyToDepart(load), Assets.ServiceTime(DefaultRS, load));
     }
 }