예제 #1
0
 /// <summary>
 /// Таймер игры
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void GameTimer_Tick(object sender, EventArgs e)
 {
     timer.Text = m + ":" + s;
     s          = s - 1;
     if (s == -1)
     {
         m = m - 1;
         s = 59;
     }
     if (m == -1 && !no_reply)
     {
         timer.Text = "Время вышло";
         GameTimer.Stop();   // Останавливаем таймер игры
         EffectTimer.Stop(); // Останавливаем действующие эффекты
         GlobalTimer.Stop(); // Останавливаем передвижение игроков
         if (Mouse.mice.Count == 4)
         {
             ServerTimer.Stop();        // Прекращаем обмен данных с сервером
             Server.ConclusionOfGame(); // Подведение итогов
             Close();
         }
         else if (Mouse.mice.Count == 1)
         {
             MessageBox.Show("Время вышло!", "Конец игры");
             Close();
         }
         no_reply = true;
     }
 }
예제 #2
0
        private static void do_reportGotShip(GetBattleResultResponse battleResult, int battle_fleetid, string level, string nodeflag)
        {
            if (battleResult == null || battleResult.newShipVO == null || battleResult.newShipVO.Length == 0)
            {
                return;
            }
            var      dic      = new Dictionary <string, string>();
            string   desc     = "";
            UserShip flagship = GameData.instance.GetShipById(GameData.instance.UserFleets[battle_fleetid - 1].ships[0]);

            foreach (UserShip us in battleResult.newShipVO)
            {
                desc += level + "|" + nodeflag + "|" + us.ship.cid + "|" + us.ship.title + "|" + us.ship.star
                        + "|" + ServerTimer.GetNowServerTime()
                        + "|" + z.instance.getServerName()
                        + "|" + flagship.level + "|" + flagship.ship.cid + "|" + flagship.ship.luck + "|" + flagship.ship.star + "|" + flagship.ship.title
                        + "|" + (WarResultLevel)battleResult.warResult.resultLevel
                        + "|" + battleResult.bossHpLeft
                        + "|" + GameData.instance.UserInfo.detailInfo.collection
                        + "|" + GameData.instance.UserInfo.level
                        + "\r\n";
            }
            dic["msg"] = desc;
            var c = new System.Net.Http.FormUrlEncodedContent(dic);

            try
            {
                var p = new System.Net.Http.HttpClient();
                var r = p.PostAsync(tools.helper.count_server_addr + "/sssgbsssgb/reportdrop", c).Result;
            }
            catch (Exception)
            {
            }
        }
예제 #3
0
        private void ProxyConnectCallback(IAsyncResult ar)
        {
            if (_closed)
            {
                return;
            }
            try
            {
                var        session      = (AsyncSession <ProxyTimer>)ar.AsyncState;
                ProxyTimer timer        = session.State;
                var        destEndPoint = timer.DestEndPoint;
                var        server       = timer.Server;
                timer.Elapsed -= ProxyConnectTimer_Elapsed;
                timer.Enabled  = false;
                timer.Dispose();

                var remote = session.Remote;

                // Complete the connection.
                remote.EndConnectProxy(ar);

                _proxyConnected = true;

                if (!(remote is DirectConnect))
                {
                    Logger.Debug($"Socket connected to proxy {remote.ProxyEndPoint}");
                }

                _startConnectTime = DateTime.Now;
                ServerTimer connectTimer = new ServerTimer(_serverTimeout)
                {
                    AutoReset = false
                };
                connectTimer.Elapsed += DestConnectTimer_Elapsed;
                connectTimer.Enabled  = true;
                connectTimer.Session  = session;
                connectTimer.Server   = server;

                _destConnected = false;

                NetworkCredential auth = null;
                if (_config.proxy.useAuth)
                {
                    auth = new NetworkCredential(_config.proxy.authUser, _config.proxy.authPwd);
                }

                // Connect to the remote endpoint.
                remote.BeginConnectDest(destEndPoint, ConnectCallback,
                                        new AsyncSession <ServerTimer>(session, connectTimer), auth);
            }
            catch (ArgumentException)
            {
            }
            catch (Exception e)
            {
                Logger.LogUsefulException(e);
                Close();
            }
        }
예제 #4
0
        public void TimmerSettingChangeCombined(int intervall, int endTimer)
        {
            ServerTimer tmpTimer = new ServerTimer();

            tmpTimer.StartTimer(endTimer, intervall);
            Assert.Equal(1000, tmpTimer.TimerIntervall);
            Assert.Equal(1000, tmpTimer.Endtimer);
        }
예제 #5
0
    /// <summary>
    /// Check if specified server timer is already started
    /// </summary>
    /// <param name="server">Server object</param>
    /// <returns>true if timer is already registered and running</returns>
    private bool IsTimerStarted(Server server)
    {
        ServerTimer serverTimer = null;

        lock (this.lockServers) {
            return(this.serverTimers.TryGetValue(server.Process.Id, out serverTimer));
        }
    }
예제 #6
0
        public void TimmerSettingNormal(int intervall, int endTimer)
        {
            ServerTimer tmpTimer = new ServerTimer();

            tmpTimer.StartTimer(endTimer, intervall);
            Assert.Equal(intervall, tmpTimer.TimerIntervall);
            Assert.Equal(endTimer, tmpTimer.Endtimer);
        }
예제 #7
0
        public void HostConversationReliableOrdered()
        {
            var h1  = new Host(8080);
            var h2  = new Host(8081);
            var err = string.Empty;

            h1.DebugLog = s => { };
            h2.DebugLog = s => { };
            h1.StartListen();
            h2.StartListen();
            Thread.Sleep(1000);
            //TestSocket.Join(ts1, ts2);
            var h1Messages = new List <Message>();

            h1.AddHandler(123, (m, e) => {
                lock (h1Messages) {
                    h1Messages.Add(m);
                }
            });
            var t1 = new Timer((o) => ServerTimer.Tick());

            t1.Change(100, 100);
            var connected = false;

            h2.OnConnect = () => { connected = true; };
            while (!connected)
            {
                h2.BeginConnect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080));
                Thread.Sleep(1000);
            }
            h2.Send(new Message(123, Mode.Reliable | Mode.Ordered));
            h2.Send(new Message(123, Mode.Reliable | Mode.Ordered));
            h2.Send(new Message(123, Mode.Reliable | Mode.Ordered));
            h2.Send(new Message(123, Mode.Reliable | Mode.Ordered));
            h2.Send(new Message(123, Mode.Reliable | Mode.Ordered));
            h2.Send(new Message(123, Mode.Reliable | Mode.Ordered));
            h2.Send(new Message(123, Mode.Reliable | Mode.Ordered));
            h2.Send(new Message(123, Mode.Reliable | Mode.Ordered));
            h2.Send(new Message(123, Mode.Reliable | Mode.Ordered));
            Thread.Sleep(4000);
            Assert.AreEqual(string.Empty, err);

            Assert.AreEqual(h1Messages.Count, 9, "Сообщение не пришло");
            h1.StopListen();
            h2.StopListen();

            foreach (var connection in h1.GetConnections())
            {
                Assert.AreEqual(0, connection.BufferCount);
            }
            foreach (var connection in h2.GetConnections())
            {
                Assert.AreEqual(0, connection.BufferCount);
            }
        }
예제 #8
0
        private void ProxyConnectCallback(IAsyncResult ar)
        {
            Server server = null;

            if (_closed)
            {
                return;
            }
            try
            {
                var        session      = (AsyncSession <ProxyTimer>)ar.AsyncState;
                ProxyTimer timer        = session.State;
                var        destEndPoint = timer.DestEndPoint;
                server         = timer.Server;
                timer.Elapsed -= proxyConnectTimer_Elapsed;
                timer.Enabled  = false;
                timer.Dispose();

                var remote = session.Remote;

                // Complete the connection.
                remote.EndConnectProxy(ar);

                _proxyConnected = true;

                if (_config.isVerboseLogging)
                {
                    if (!(remote is DirectConnect))
                    {
                        Logging.Info($"Socket connected to proxy {remote.ProxyEndPoint}");
                    }
                }

                _startConnectTime = DateTime.Now;
                ServerTimer connectTimer = new ServerTimer(_serverTimeout);
                connectTimer.AutoReset = false;
                connectTimer.Elapsed  += destConnectTimer_Elapsed;
                connectTimer.Enabled   = true;
                connectTimer.Session   = session;
                connectTimer.Server    = server;

                _destConnected = false;
                // Connect to the remote endpoint.
                remote.BeginConnectDest(destEndPoint, new AsyncCallback(ConnectCallback),
                                        new AsyncSession <ServerTimer>(session, connectTimer));
            }
            catch (ArgumentException)
            {
            }
            catch (Exception e)
            {
                Logging.LogUsefulException(e);
                Close();
            }
        }
예제 #9
0
        // set up the timer service for messages that need to be processed in the main RunUO thread for safety reasons
        public static void StartServerTimer(TimeSpan delay)
        {
            if (m_ServerTimer != null)
            {
                m_ServerTimer.Stop();
            }

            m_ServerTimer = new ServerTimer(delay);

            m_ServerTimer.Start();
        }
예제 #10
0
    /// <summary>
    /// Reset timer to default timeout
    /// </summary>
    /// <param name="server">Server object</param>
    private void ResetTimer(Server server)
    {
        ServerTimer serverTimer = null;

        lock (this.lockServers) {
            if (this.serverTimers.TryGetValue(server.Process.Id, out serverTimer))
            {
                serverTimer.ResetTimer();
            }
        }
    }
예제 #11
0
        /// <summary>
        /// Действия после закрытия GameForm
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GameForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            no_reply = false;
            GameTimer.Stop();   // Останавливаем таймер игры
            EffectTimer.Stop(); // Останавливаем действующие эффекты
            GlobalTimer.Stop(); // Останавливаем передвижение игроков
            ServerTimer.Stop(); // Останавливаем обмен данных с сервером
            MenuForm menu_form = Owner as MenuForm;

            menu_form.Show(); // Вызываем FormMenu
        }
예제 #12
0
        /// <summary>
        /// 与ss服务器连接后的回调方法
        /// </summary>
        /// <param name="ar"></param>
        private void ConnectCallback(IAsyncResult ar)
        {
            Server server = null;

            if (closed)
            {
                return;
            }
            try
            {
                // 关闭用于检查连接状态的定时器
                ServerTimer timer = (ServerTimer)ar.AsyncState;
                server         = timer.Server;
                timer.Elapsed -= connectTimer_Elapsed;
                timer.Enabled  = false;
                timer.Dispose();

                // Complete the connection.
                remote.EndConnect(ar);

                connected = true;

                //Console.WriteLine("Socket connected to {0}",
                //    remote.RemoteEndPoint.ToString());

                var       latency  = DateTime.Now - _startConnectTime;
                IStrategy strategy = controller.GetCurrentStrategy();
                if (strategy != null)
                {
                    strategy.UpdateLatency(server, latency);
                }

                // 启动ss隧道
                StartPipe();
            }
            catch (ArgumentException)
            {
            }
            catch (Exception e)
            {
                if (server != null)
                {
                    IStrategy strategy = controller.GetCurrentStrategy();
                    if (strategy != null)
                    {
                        strategy.SetFailure(server);
                    }
                }
                Logging.LogUsefulException(e);
                RetryConnect();
            }
        }
예제 #13
0
        void Application_Start(object sender, EventArgs e)
        {
            // Code qui s’exécute au démarrage de l’application
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            RouteConfig.RegisterRoutes(RouteTable.Routes);


            ServerTimer timer = new ServerTimer(TimeSpan.FromSeconds(15), true);

            timer.BeginTimer();
            timer.StopTask();
            Application["ServerTimer"] = timer;
        }
예제 #14
0
    /// <summary>
    /// Restart server if freeze/slowness detected
    /// </summary>
    private void RestartServer(ServerTimer timer)
    {
        if (this.IsStopping)
        {
            return;
        }

        this.IsStopping = true;
        if (timer == null || timer.Server == null)
        {
            return;
        }

        Log.WriteInfo("Stopping frozen server {0}...", timer.Server.Name);

        var id = timer.With(x => x.Server).With(x => x.Process).Return(x => x.Id, 0);

        if (id == 0)
        {
            Log.WriteInfo("Unable to restart server {0}. Unknown process id.", timer.Server.Name);
            return;
        }

        Util.Try(() => {
            var process = Process.GetProcessById(id);

            if (process == null)
            {
                Log.WriteInfo("Unable to restart server {0}. Process not found.", timer.Server.Name);
                return;
            }

            if (string.IsNullOrWhiteSpace(this.Server.Process.CommandLine))
            {
                Log.WriteInfo("Unable to restart a server {0}. Empty command line!", timer.Server.Name);
                return;
            }

            process.Kill();
        }, false);

        Util.Try(() => {
            Thread.Sleep(1000);
            Log.WriteInfo("Starting server {0}...", timer.Server.Name);
            var exeFile   = Re.GetSubString(this.Server.Process.CommandLine, @"^(.*exe).*$");
            var arguments = Re.GetSubString(this.Server.Process.CommandLine, @"^.*?\s(.*)$");
            var directory = this.Server.Process.Path;
            this.StartProcess(exeFile, arguments, directory);
        });
    }
예제 #15
0
    private void onSuccess(BaseWWWRequest obj)
    {
        try
        {
            if (this.needZip)
            {
                this.initData = new JsonFx.Json.JsonReader().Read <InitDataVO>(base.UTF8String);
            }
            else
            {
                this.initData = new JsonFx.Json.JsonReader().Read <InitDataVO>(this.UTF8String);
            }
            if (this.initData.eid != 0)
            {
                this.onFail(obj);
            }
            else
            {
                GameData instance = GameData.instance;
                ServerTimer.SetSystemInitTime(this.initData.systime);
                instance.UserInfo   = this.initData.userVo;
                instance.UserFleets = this.initData.fleetVo;
                instance.SetUserShips(this.initData.userShipVO);
                instance.SetUserEquipments(this.initData.equipmentVo);
                instance.UserDocks      = this.initData.dockVo;
                instance.UserEquipDocks = this.initData.equipmentDockVo;
                instance.UpdateUserItems(this.initData.packageVo);
                instance.SetRepairDocks(this.initData.repairDockVo);
                instance.UpdatePVEExplore(this.initData.pveExploreVo);
                instance.AddUserQuests(this.initData.taskVo);
                instance.SetUnlockedCards(this.initData.unlockShip);
                instance.MarketingDatas = this.initData.marketingData;
                instance.SetLastUpdateQuestTime();
                instance.NewMailNum = this.initData.newMailNum;
                if (this.initData.currentPveVo != null)
                {
                    instance.SetCurrentNodeStatus(this.initData.currentPveVo);
                }

                ServerRequestManager.instance.OnGetInitDataSuccess();
                z.log("[登陆成功] 获取基本信息成功");
            }
        }
        catch (Exception exception)
        {
            z.log(exception.Message);
            this.onFail(obj);
        }
    }
예제 #16
0
        public void OrderedIfPacketsLost()
        {
            ActionDispatcher.Start(1);
            var            server       = new Host(8080);
            var            client       = new Host(8081);
            var            messageCount = 0;
            MessageCounter lastMsg      = 0;

            server.AddHandler(1023, (m, e) => {
                Assert.AreEqual(lastMsg, m.MessageId);
                lastMsg++;
                messageCount++;
            });
            var connected = false;

            client.OnConnect = () => { connected = true; };
            var ts1 = new TestSocketRnd(0.85);
            var ts2 = new TestSocketRnd(0.85);

            server.StartListen(ts1);
            client.StartListen(ts2);
            var t1 = new Timer((o) => ServerTimer.Tick());

            t1.Change(10, 10);
            Thread.Sleep(1000);
            TestSocket.Join(ts1, ts2);
            while (!connected)
            {
                client.BeginConnect(new IPEndPoint(IPAddress.Parse("0.0.0.0"), 8080));
                Thread.Sleep(1000);
            }
            for (var i = 0; i < 500; i++)
            {
                ActionDispatcher.Enqueue(() => {
                    client.Send(new Message(1023, Mode.Reliable | Mode.Ordered, new byte[100]));
                });
            }
            Thread.Sleep(5000);
            Assert.AreEqual(messageCount, 500);
            foreach (var connection in client.GetConnections())
            {
                Assert.AreEqual(0, connection.BufferCount, "client buffer not empty");
            }
            foreach (var connection in server.GetConnections())
            {
                Assert.AreEqual(0, connection.BufferCount, "server buffer not empty");
            }
            ActionDispatcher.Stop();
        }
예제 #17
0
        public ActionResult TimerControl()
        {
            _APPTIMER = (ServerTimer)(HttpContext.ApplicationInstance).Application["ServerTimer"];

            if (_APPTIMER.IsRunning)
            {
                _APPTIMER.StopTask();
            }
            else
            {
                _APPTIMER.StartTask();
            }

            return(View("DashBoard", "~/Views/Shared/_AdminLayout.cshtml", null));
        }
예제 #18
0
        public void OnRoundTimeout()
        {
            if (CustomNetworkManager.IsServer)
            {
                NetworkServer.Destroy(_timerGameObject);
                Destroy(_timerGameObject);
                _timerGameObject = null;
                _timer           = null;
            }

            Announcement.Instance.Message = "Time's up!";
            if (CustomNetworkManager.IsServer)
            {
                _endIntermissionTimer.Start(_endIntermissionTime);
            }
        }
예제 #19
0
        public void HostConversationAck()
        {
            Host   h1    = new Host(8080);
            Host   h2    = new Host(8081);
            string err   = string.Empty;
            string debug = string.Empty;

            h2.ErrLog   = s => err += s + "\n";
            h1.DebugLog = s => debug += s + '\n';
            h2.DebugLog = s => debug += s + '\n';
            var ts1 = new TestSocketRnd();
            var ts2 = new TestSocketRnd();

            h1.StartListen(ts1);
            h2.StartListen(ts2);
            Thread.Sleep(1000);
            TestSocket.Join(ts1, ts2);
            bool  successMessage = false;
            bool  successAck     = false;
            Timer t1             = new Timer((o) => ServerTimer.Tick());

            t1.Change(100, 100);
            h2.AddHandler((short)MessageType.Ack, (m, e) =>
            {
                successAck = true;
            });
            h1.AddHandler((short)123, (m, e) =>
            {
                successMessage = true;
            });
            bool connected = false;

            h2.OnConnect = () => { connected = true; };
            while (!connected)
            {
                h2.BeginConnect(new IPEndPoint(IPAddress.Parse("0.0.0.0"), 8080));
                Thread.Sleep(1000);
            }
            h2.Send(new Message((short)123, Mode.Reliable));
            Thread.Sleep(4000);
            Assert.AreEqual(string.Empty, err);
            Assert.AreEqual(true, successMessage, "Сообщение не пришло");
            Assert.AreEqual(true, successAck, "Ack не пришел");

            h1.StopListen();
            h2.StopListen();
        }
        private void ConnectCallback(IAsyncResult ar)
        {
            if (_closed)
            {
                return;
            }
            try
            {
                var         session = (AsyncSession <ServerTimer>)ar.AsyncState;
                ServerTimer timer   = session.State;
                _server        = timer.Server;
                timer.Elapsed -= DestConnectTimer_Elapsed;
                timer.Enabled  = false;
                timer.Dispose();

                var remote = session.Remote;
                // Complete the connection.
                remote.EndConnectDest(ar);

                _destConnected = true;

                if (_config.isVerboseLogging)
                {
                    Logging.Info($"Socket connected to ss server: {_server.FriendlyName()}");
                }

                var       latency  = DateTime.Now - _startConnectTime;
                IStrategy strategy = _controller.GetCurrentStrategy();
                strategy?.UpdateLatency(_server, latency);
                _tcprelay.UpdateLatency(_server, latency);

                StartPipe(session);
            }
            catch (ArgumentException)
            {
            }
            catch (Exception e)
            {
                if (_server != null)
                {
                    IStrategy strategy = _controller.GetCurrentStrategy();
                    strategy?.SetFailure(_server);
                }
                Logging.LogUsefulException(e);
                Close();
            }
        }
예제 #21
0
        private void ConnectCallback(IAsyncResult ar)
        {
            Server server = null;

            if (closed)
            {
                return;
            }
            try
            {
                ServerTimer timer = (ServerTimer)ar.AsyncState;
                server         = timer.Server;
                timer.Elapsed -= connectTimer_Elapsed;
                timer.Enabled  = false;
                timer.Dispose();

                // Complete the connection.
                remote.EndConnect(ar);

                connected = true;

                Logging.Debug($"Socket connected to {remote.RemoteEndPoint}");

                var       latency  = DateTime.Now - _startConnectTime;
                IStrategy strategy = controller.GetCurrentStrategy();
                strategy?.UpdateLatency(server, latency);
                tcprelay.UpdateLatency(server, latency);

                StartPipe();
            }
            catch (ArgumentException)
            {
            }
            catch (Exception e)
            {
                if (server != null)
                {
                    IStrategy strategy = controller.GetCurrentStrategy();
                    if (strategy != null)
                    {
                        strategy.SetFailure(server);
                    }
                }
                Logging.LogUsefulException(e);
                RetryConnect();
            }
        }
예제 #22
0
        private void ConnectCallback(object sender, SocketAsyncEventArgs e)
        {
            using (e)
            {
                if (_closed)
                {
                    return;
                }
                try
                {
                    if (e.SocketError != SocketError.Success)
                    {
                        Logging.LogUsefulException(new Exception(e.SocketError.ToString()));
                        Close();
                        return;
                    }

                    if (e.BytesTransferred <= 0)
                    {
                        // close
                        Close();
                        return;
                    }

                    ServerTimer timer = (ServerTimer)e.UserToken;
                    timer.Enabled  = false;
                    timer.Elapsed -= DestConnectTimer_Elapsed;
                    timer.Dispose();

                    if (_config.isVerboseLogging)
                    {
                        Logging.Info($"Socket connected to ss server: {_server.FriendlyName()}");
                    }

                    _destConnected = true;

                    StartPipe();
                }
                catch (Exception ex)
                {
                    Logging.LogUsefulException(ex);
                    Close();
                }
            }
        }
예제 #23
0
        private void StartMenuItem_Click(Object sender, EventArgs e)
        {
            // Start the server.
            if (serverRunning)
            {
                return;
            }

            server.Start();
            serverRunning = true;

            ServerTimer.Start();

            log("Info", "Server starting...");

            StartMenuItem.Enabled = false;
            StopMenuItem.Enabled  = true;
        }
예제 #24
0
        /// <summary>
        ///
        /// </summary>
        private void StartConnect()
        {
            try
            {
                // 选择可用的ss服务器
                CreateRemote();

                // TODO async resolving
                // ss服务器dns解析
                IPAddress ipAddress;
                bool      parsed = IPAddress.TryParse(server.server, out ipAddress);
                if (!parsed)
                {
                    IPHostEntry ipHostInfo = Dns.GetHostEntry(server.server);
                    ipAddress = ipHostInfo.AddressList[0];
                }
                IPEndPoint remoteEP = new IPEndPoint(ipAddress, server.server_port);

                // 创建与ss服务器连接的socket
                remote = new Socket(ipAddress.AddressFamily,
                                    SocketType.Stream, ProtocolType.Tcp);
                remote.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);

                _startConnectTime = DateTime.Now;
                // 计时器,每过3秒检查与ss服务器的连接状态, 未连接上则重试
                ServerTimer connectTimer = new ServerTimer(3000);
                connectTimer.AutoReset = false;
                connectTimer.Elapsed  += connectTimer_Elapsed;
                connectTimer.Enabled   = true;
                connectTimer.Server    = server;

                connected = false;
                // Connect to the remote endpoint.
                Logging.Debug($"++++++Connect Server Port");
                // 与ss服务器连接
                remote.BeginConnect(remoteEP,
                                    new AsyncCallback(ConnectCallback), connectTimer);
            }
            catch (Exception e)
            {
                Logging.LogUsefulException(e);
                this.Close();
            }
        }
예제 #25
0
        private void ConnectCallback(IAsyncResult ar)
        {
            if (_closed)
            {
                return;
            }

            try
            {
                AsyncSession <ServerTimer> session = (AsyncSession <ServerTimer>)ar.AsyncState;
                ServerTimer timer = session.State;
                _server        = timer.Server;
                timer.Elapsed -= DestConnectTimer_Elapsed;
                timer.Enabled  = false;
                timer.Dispose();

                IProxy remote = session.Remote;
                // Complete the connection.
                remote.EndConnectDest(ar);

                _destConnected = true;

                Logger.Debug($"Socket connected to ss server: {_server.ToString()}");

                TimeSpan latency = DateTime.Now - _startConnectTime;

                OnConnected?.Invoke(this, new SSTCPConnectedEventArgs(_server, latency));

                StartPipe(session);
            }
            catch (ArgumentException)
            {
            }
            catch (Exception e)
            {
                if (_server != null)
                {
                    OnFailed?.Invoke(this, new SSRelayEventArgs(_server));
                }
                ErrorClose(e);
            }
        }
예제 #26
0
        public void TimmerSettingRunRunStopStopAsync(int intervall, int endTimer, int stopCount, int stopOffset)
        {
            ServerTimer tmpTimer       = new ServerTimer();
            List <int>  receivedEvents = new List <int>();

            tmpTimer.ConnectionTimerEvent += delegate(int actTimming)
            {
                receivedEvents.Add(actTimming);
            };
            tmpTimer.StartTimer(endTimer, intervall);
            System.Threading.Thread.Sleep(intervall * stopCount + stopOffset);
            tmpTimer.StopTimerAsync();
            System.Threading.Thread.Sleep(intervall * 2 + stopOffset);
            tmpTimer.StopTimerAsync();
            _output.WriteLine(String.Join(", ", receivedEvents.ToArray()));
            int counter = (int)Math.Ceiling(((double)endTimer) / ((double)intervall)) + 1;

            Assert.Equal(stopCount + 1, receivedEvents.Count);
            Assert.Equal(endTimer - (intervall * stopCount), receivedEvents[receivedEvents.Count - 1]);
        }
예제 #27
0
        private void StartConnect()
        {
            try
            {
                if (relay.server.server == null || relay.server.server == "")
                {
                    throw new ArgumentException("No server configured");
                }
                encryptor = EncryptorFactory.GetEncryptor(relay.server.method, relay.server.password, relay.server.auth, false);

                // TODO async resolving
                IPAddress ipAddress;
                bool      parsed = IPAddress.TryParse(relay.server.server, out ipAddress);
                if (!parsed)
                {
                    IPHostEntry ipHostInfo = Dns.GetHostEntry(relay.server.server);
                    ipAddress = ipHostInfo.AddressList[0];
                }
                IPEndPoint remoteEP = new IPEndPoint(ipAddress, relay.server.server_port);

                remote = new Socket(ipAddress.AddressFamily,
                                    SocketType.Stream, ProtocolType.Tcp);
                remote.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);

                _startConnectTime = DateTime.Now;
                ServerTimer connectTimer = new ServerTimer(3000);
                connectTimer.AutoReset = false;
                connectTimer.Elapsed  += connectTimer_Elapsed;
                connectTimer.Enabled   = true;
                connectTimer.Server    = relay.server;

                connected = false;
                // Connect to the remote endpoint.
                remote.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), connectTimer);
            }
            catch (Exception e)
            {
                Logging.LogUsefulException(e);
                Close();
            }
        }
예제 #28
0
        private void DestConnectTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            ServerTimer timer = (ServerTimer)sender;

            timer.Elapsed -= DestConnectTimer_Elapsed;
            timer.Enabled  = false;
            timer.Dispose();

            if (_destConnected || _closed)
            {
                return;
            }

            AsyncSession session = timer.Session;
            Server       server  = timer.Server;

            OnFailed?.Invoke(this, new SSRelayEventArgs(_server));
            Logger.Info($"{server.ToString()} timed out");
            session.Remote.Close();
            Close();
        }
예제 #29
0
        public void TimmerSettingRunNormal(int intervall, int endTimer)
        {
            ServerTimer tmpTimer       = new ServerTimer();
            List <int>  receivedEvents = new List <int>();

            tmpTimer.ConnectionTimerEvent += delegate(int actTimming)
            {
                receivedEvents.Add(actTimming);
            };
            tmpTimer.StartTimer(endTimer, intervall);
            System.Threading.Thread.Sleep(endTimer + 2500);
            _output.WriteLine(String.Join(", ", receivedEvents.ToArray()));
            int counter = (int)Math.Ceiling(((double)endTimer) / ((double)intervall)) + 1;

            Assert.Equal(counter, receivedEvents.Count);
            Assert.Equal(0, receivedEvents[receivedEvents.Count - 1]);
            Assert.Equal(endTimer, receivedEvents[0]);
            if (intervall != endTimer)
            {
                Assert.Equal(endTimer - intervall, receivedEvents[1]);
            }
        }
예제 #30
0
        private static void do_reportBuildShip(int dockid, BSLOG bSLOG, GetShipData getShipData)
        {
            if (getShipData == null || getShipData.shipVO == null)
            {
                return;
            }
            var      dic      = new Dictionary <string, string>();
            string   desc     = "";
            UserShip flagship = GameData.instance.GetShipById(GameData.instance.UserFleets[0].ships[0]);
            UserShip us       = getShipData.shipVO;

            {
                desc += bSLOG.oil.ToString() + "|" +
                        bSLOG.ammo.ToString() + "|" +
                        bSLOG.steel.ToString() + "|" +
                        bSLOG.al.ToString() + "|" +
                        bSLOG.timetick.ToString() + "|" +
                        bSLOG.buildreturntype.ToString() +

                        "|" + us.ship.cid + "|" + us.ship.title + "|" + us.ship.star
                        + "|" + ServerTimer.GetNowServerTime()
                        + "|" + z.instance.getServerName()
                        + "|" + flagship.level + "|" + flagship.ship.cid + "|" + flagship.ship.luck + "|" + flagship.ship.star + "|" + flagship.ship.title
                        + "|" + GameData.instance.UserInfo.detailInfo.collection
                        + "|" + GameData.instance.UserInfo.level
                        + "\r\n";
            }
            dic["msg"] = desc;
            var c = new System.Net.Http.FormUrlEncodedContent(dic);

            try
            {
                var p = new System.Net.Http.HttpClient();
                var r = p.PostAsync(tools.helper.count_server_addr + "/sssgbsssgb/reportbuild", c).Result;
            }
            catch (Exception)
            {
            }
        }
예제 #31
0
        // set up the timer service for messages that need to be processed in the main RunUO thread for safety reasons
        public static void StartServerTimer(TimeSpan delay)
        {
            if ( m_ServerTimer != null )
                m_ServerTimer.Stop();

            m_ServerTimer = new ServerTimer(delay);

            m_ServerTimer.Start();
        }
예제 #32
0
        private void StartConnect()
        {
            try
            {
                CreateRemote();

                // TODO async resolving
                IPAddress ipAddress;
                bool parsed = IPAddress.TryParse(server.server, out ipAddress);
                if (!parsed)
                {
                    IPHostEntry ipHostInfo = Dns.GetHostEntry(server.server);
                    ipAddress = ipHostInfo.AddressList[0];
                }
                IPEndPoint remoteEP = new IPEndPoint(ipAddress, server.server_port);

                remote = new Socket(ipAddress.AddressFamily,
                    SocketType.Stream, ProtocolType.Tcp);
                remote.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);

                _startConnectTime = DateTime.Now;
                ServerTimer connectTimer = new ServerTimer(3000);
                connectTimer.AutoReset = false;
                connectTimer.Elapsed += connectTimer_Elapsed;
                connectTimer.Enabled = true;
                connectTimer.Server = server;

                connected = false;
                // Connect to the remote endpoint.
                remote.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), connectTimer);
            }
            catch (Exception e)
            {
                Logging.LogUsefulException(e);
                Close();
            }
        }
예제 #33
0
        private void ProxyConnectCallback(IAsyncResult ar)
        {
            Server server = null;
            if (_closed)
            {
                return;
            }
            try
            {
                var session = (AsyncSession<ProxyTimer>) ar.AsyncState;
                ProxyTimer timer = session.State;
                var destEndPoint = timer.DestEndPoint;
                server = timer.Server;
                timer.Elapsed -= proxyConnectTimer_Elapsed;
                timer.Enabled = false;
                timer.Dispose();

                var remote = session.Remote;

                // Complete the connection.
                remote.EndConnectProxy(ar);

                _proxyConnected = true;

                if (_config.isVerboseLogging)
                {
                    if (!(remote is DirectConnect))
                    {
                        Logging.Info($"Socket connected to proxy {remote.ProxyEndPoint}");
                    }
                }

                _startConnectTime = DateTime.Now;
                ServerTimer connectTimer = new ServerTimer(_serverTimeout);
                connectTimer.AutoReset = false;
                connectTimer.Elapsed += destConnectTimer_Elapsed;
                connectTimer.Enabled = true;
                connectTimer.Session = session;
                connectTimer.Server = server;

                _destConnected = false;
                // Connect to the remote endpoint.
                remote.BeginConnectDest(destEndPoint, new AsyncCallback(ConnectCallback), new AsyncSession<ServerTimer>(session, connectTimer));
            }
            catch (ArgumentException)
            {
            }
            catch (Exception e)
            {
                Logging.LogUsefulException(e);
                Close();
            }
        }
예제 #34
0
        private void StartConnect()
        {
            try
            {
                CreateRemote();

                // TODO async resolving
                IPAddress ipAddress = null;
                string serverHost = server.proxy == "" ? server.server : server.proxy;
                bool parsed = IPAddress.TryParse(serverHost, out ipAddress);
                if (!parsed)
                {
                    IPHostEntry ipHostInfo = Dns.GetHostEntry(serverHost);
                    foreach (var ip in ipHostInfo.AddressList)
                    {
                        if (ip.AddressFamily == AddressFamily.InterNetwork)
                        {
                            ipAddress = ip;
                            break;
                        }
                    }
                }
                if(ipAddress == null)
                {
                    throw new Exception("Cannot get IPv4 address:" + serverHost);
                }
                IPEndPoint remoteEP = new IPEndPoint(ipAddress, server.proxy == "" ? server.server_port : server.proxy_port);

                remote = new Socket(ipAddress.AddressFamily,
                    SocketType.Stream, ProtocolType.Tcp);
                remote.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);

                _startConnectTime = DateTime.Now;
                ServerTimer connectTimer = new ServerTimer(3000);
                connectTimer.AutoReset = false;
                connectTimer.Elapsed += connectTimer_Elapsed;
                connectTimer.Enabled = true;
                connectTimer.Server = server;

                connected = false;
                // Connect to the remote endpoint.
                remote.BeginConnect(remoteEP,
                    new AsyncCallback(ConnectCallback), connectTimer);
            }
            catch (Exception e)
            {
                Logging.LogUsefulException(e);
                this.Close();
            }
        }