static void Main(string[] args) { Debug.Log("请输入 UDP 服务监听的端口 缺省值为12800"); string udp_port = Console.ReadLine(); ushort udpPort = 12800; if (ushort.TryParse(udp_port, out var result_udpPort)) { udpPort = result_udpPort; } UDPServer udpServer = new UDPServer(udpPort); Network network = new Network(udpServer); //启动udp接收消息的线程 ThreadPool.QueueUserWorkItem(ServerUdpServerThread, udpServer); while (true) { network.Update(); Thread.Sleep(10); GC.Collect(); } }
public void Update() { if (Network != null) { Network.Update(); } }
/// <summary> /// Creates a new default game loop. /// </summary> public GameLoop() { #if EDITOR if (GameEngine.Engine.LevelEditMode && !Screen.IsFullHeadless) { //Add(DefaultEnum.LevelEditor, LevelEditor.Update); } #endif Add(DefaultEnum.Time, () => Time.Update(GameEngine.Engine.GameTime)); Add(DefaultEnum.Physics, Core.Physics.Update); Add(DefaultEnum.UpdateDynamicGameObjects, GameEngine.Engine.UpdateDynamicGameObjects); Add(DefaultEnum.Networking, () => Network.Update(Time.UnscaledDeltaTime)); Add(DefaultEnum.UpdateLevelManager, SceneManager.Update); Add(DefaultEnum.SpatialPartition, SpatialPartitionManager.Update); Add(DefaultEnum.Console, Console.Update); Add(DefaultEnum.FinalizeTime, Time.FinalizeFixedTimeStep); if (!Screen.IsFullHeadless) { Add(DefaultEnum.StartNewParticles, () => ParticleEngine.Update(Time.DeltaTime, Core.Rendering.CameraBounds[0])); Add(DefaultEnum.InputManager, () => InputManager.Update(Time.UnscaledDeltaTime)); Add(DefaultEnum.UIManager, UIManager.Update); Add(DefaultEnum.Screen, Screen.Update); Add(DefaultEnum.RenderingSystem, Core.Rendering.Update); } }
public static void TimerTick() { serverLevel.UpdateFirst(); Network.Update(); serverLevel.Update(); Thread.Sleep(16); //ca 60 tick }
public override void Update() { if (Network != null) { Network.Update(); } }
/// <summary> /// This is run in parallel from our main loop. /// </summary> public void TickInParallel(double lastTickDuration) { // Checks if the session has stopped responding. if (DateTime.UtcNow.Ticks >= Network.TimeoutTick) { // Change the state to show that the Session has reached a timeout. State = SessionState.NetworkTimeout; } Network.Update(lastTickDuration); // Live server seemed to take about 6 seconds. 4 seconds is nice because it has smooth animation, and saves the user 2 seconds every logoff // This could be made 0 for instant logoffs. if (logOffRequestTime != DateTime.MinValue && logOffRequestTime.AddSeconds(6) <= DateTime.UtcNow) { logOffRequestTime = DateTime.MinValue; SendFinalLogOffMessages(); } // Check if the player has been booted if (bootSession) { SendFinalBoot(); State = SessionState.NetworkTimeout; } }
public override void Update(int delta) { if (_net != null) { _net.Update(); } }
void Update() { if (_net != null && _net.IsConnected()) { _net.Update(); } if (player.transform.position.y < -1.0f) { CanvasGroup imageCanvasGroup = endpanel.GetComponent <CanvasGroup>(); _endtimer += Time.deltaTime; imageCanvasGroup.alpha = _endtimer / _fadeDuration; if (_endtimer > _fadeDuration + _displayImageDuration) { Application.Quit(); } } List <string> roomlines = new List <string>(); roomlines.Add("Room:"); foreach (var e in _players) { string id = e.Key; string score = e.Value.GetComponent <Player>().GetScore().ToString(); roomlines.Add(id + ":" + score); } string room = String.Join("\n", roomlines.ToArray()); GameObject panel = GameObject.FindGameObjectWithTag("Panel"); Panel panelsc = panel.GetComponent <Panel>(); panelsc.UpdateRoom(room); }
protected override void Update(GameTime gameTime) { var keyboardState = Keyboard.GetState(); if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || keyboardState.IsKeyDown(Keys.Escape)) { Exit(); } if (!_started) { if (keyboardState.IsKeyDown(Keys.D1)) { StartGame(true); } else if (keyboardState.IsKeyDown(Keys.D2)) { StartGame(false); } return; } Network.Update((float)gameTime.TotalGameTime.TotalMilliseconds); foreach (var actor in Actors) { actor.Update(gameTime, IsActive, Actors); } base.Update(gameTime); }
private void TimerTick_Tick(object sender, EventArgs e) { try { network.Update(); //string s = $"Upload:{network.GetUploadSpeed()} Download:{network.GetDownloadSpeed()}"; if (this.Visibility == Visibility.Visible) { //string s_1 = "Sent: " + network.ConvertTo(network.GetSentAndReceivedbytes().Item1, debug_mode); //string s_2 = "Received: " + network.ConvertTo(network.GetSentAndReceivedbytes().Item2, debug_mode); //Debug.Content = $"{s_1} {s_2}"; Debug.Content = network.GetbytesSentAndReceived(debug_mode); Debug2.Content = network.GetUploadAndDownloadSpeed("\n"); Debug3.Content = network.GetIncomingPacketsWithErrors(); } notify.Text = network.GetUploadAndDownloadSpeed(); if (windinfo.IsClosed == false) { windinfo.SetText(network.GetUploadAndDownloadSpeed(" ")); } } catch (Exception) { Err(); } }
private float TrainNetwork(INetworkRunContext context, IEnumerable <float> inputs, float target) { context.Set(inputs.Take(context.InputCount)); context.Target[0] = target; neuralNetwork.Train(context); neuralNetwork.Update(); return(context.TotalError); }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void UpdateTimer_Tick(object sender, EventArgs e) { TimeSpan elapsed = DateTime.Now - LastUpdate; LastUpdate = DateTime.Now; Network.Update(elapsed); }
public void DoSomethingWithNote(Session session, Note note) { Network net = new Network(); IDeserialize des = new JsConvert(); net.Update(note.id, des.SerializeObj(note)); session.state = new StateMainWindow(session); }
/// <summary> /// This will send outgoing packets as well as the final logoff message. /// </summary> public void TickOutbound() { // Check if the player has been booted if (PendingTermination != null) { if (PendingTermination.TerminationStatus == SessionTerminationPhase.Initialized) { State = SessionState.TerminationStarted; Network.Update(); // boot messages may need sending if (DateTime.UtcNow.Ticks > PendingTermination.TerminationEndTicks) { PendingTermination.TerminationStatus = SessionTerminationPhase.SessionWorkCompleted; } } return; } if (State == SessionState.TerminationStarted) { return; } // Checks if the session has stopped responding. if (DateTime.UtcNow.Ticks >= Network.TimeoutTick) { // The Session has reached a timeout. Send the client the error disconnect signal, and then drop the session Terminate(SessionTerminationReason.NetworkTimeout); return; } Network.Update(); // Live server seemed to take about 6 seconds. 4 seconds is nice because it has smooth animation, and saves the user 2 seconds every logoff // This could be made 0 for instant logoffs. if (logOffRequestTime != DateTime.MinValue && logOffRequestTime.AddSeconds(6) <= DateTime.UtcNow) { SendFinalLogOffMessages(); } // This section deviates from known retail pcaps/behavior, but appears to be the least harmful way to work around something that seemingly didn't occur to players using ThwargLauncher connecting to retail servers. // In order to prevent the launcher from thinking the session is dead, we will send a Ping Response every 100 seconds, this will in effect make the client appear active to the launcher and allow players to create characters in peace. if (State == SessionState.AuthConnected) // TODO: why is this needed? Why didn't retail have this problem? Is this fuzzy memory? { if (lastCharacterSelectPingReply == DateTime.MinValue) { lastCharacterSelectPingReply = DateTime.UtcNow.AddSeconds(100); } else if (DateTime.UtcNow > lastCharacterSelectPingReply) { Network.EnqueueSend(new GameEventPingResponse(this)); lastCharacterSelectPingReply = DateTime.UtcNow.AddSeconds(100); } } else if (lastCharacterSelectPingReply != DateTime.MinValue) { lastCharacterSelectPingReply = DateTime.MinValue; } }
public override void Update() { if (Network != null) { Network.Update(); if (this.IsConnected) { this.LastConnectTime = DateTime.Now; } } }
static void Main(string[] args) { int serverid = net.Connect("127.0.0.1", 12345); net.DefaultServerID = serverid; LoginExample(); while (true) { net.Update(); } }
private void btnDialogOk_Click(object sender, RoutedEventArgs e) { if (commPort.Text != "") { _network = new Network(null); _network.Update(providers.Content.ToString(), commPort.Text); System.Windows.MessageBox.Show("Updated"); this.DialogResult = true; } else { MessageBox.Show("please input the port !"); } }
void OnDrawGizmos() { if (network == null) { return; } // Update and display the Network network.Update(); network.Display(); ////Every 30 frame feed an Input if (Time.frameCount % 30 == 0) { network.Feedforward(Random.value, 0); } }
static void Main(string[] args) { Debug.Log("请输入服务器的IP地址 缺省值为127.0.0.1"); string ip = Console.ReadLine(); if (string.IsNullOrEmpty(ip.Trim())) { ip = "127.0.0.1"; } Debug.Log("请输入 UDP 服务监听的端口 缺省值为12800"); string udp_port = Console.ReadLine(); ushort udpPort = 12800; if (ushort.TryParse(udp_port, out var result_udpPort)) { udpPort = result_udpPort; } UdpClientSession clientSession = new UdpClientSession(ip, udpPort); KcpSession kcpsession = new KcpSession(); Network network = new Network(clientSession, kcpsession); int heartbeat = 0; while (true) { if (kcpsession.GetConv > 0) { heartbeat++; if (heartbeat > 100) { heartbeat = 0; byte[] buffer = BitConverter.GetBytes(kcpsession.GetConv); EventSystem.DispatchEvent(EventID.send_kcp_buffer, buffer); } } Thread.Sleep(10); network.Update(); GC.Collect(); } }
public Server() { Console.WriteLine("NetGame Server (" + Universal.GAME_VERSION + ")"); string serverName = "My Server"; random = new Random(); world = new World(); network = new Network(); network.Start(world, serverName); world.SetNetwork(network); updateTimer = new Timer(1000 / Universal.FRAME_RATE); updateTimer.Elapsed += new ElapsedEventHandler(UpdateElapsed); updateTimer.Start(); while (true) { network.Update(); } }
public void Update(float elapsed) { if (SyncTimer.IsElapsed(elapsed)) { ClientContent.Synchronise(); } Network.Update(); ReturnContent.Synchronise(); foreach (SyncHandle handle in ReturnContent.Handles) { if (handle.Updated) { if (handle.Obj is LocalPlayer request) { Player.UpdateWithMotionRequest(request); } } } }
/// <summary> /// This will send outgoing packets as well as the final logoff message. /// </summary> public void TickOutbound() { // Check if the player has been booted if (PendingTermination != null) { if (PendingTermination.TerminationStatus == SessionTerminationPhase.Initialized) { State = SessionState.TerminationStarted; Network.Update(); // boot messages may need sending if (DateTime.UtcNow.Ticks > PendingTermination.TerminationEndTicks) { PendingTermination.TerminationStatus = SessionTerminationPhase.SessionWorkCompleted; } } return; } if (State == SessionState.TerminationStarted) { return; } // Checks if the session has stopped responding. if (DateTime.UtcNow.Ticks >= Network.TimeoutTick) { // The Session has reached a timeout. Send the client the error disconnect signal, and then drop the session Terminate(SessionTerminationReason.NetworkTimeout); return; } Network.Update(); // Live server seemed to take about 6 seconds. 4 seconds is nice because it has smooth animation, and saves the user 2 seconds every logoff // This could be made 0 for instant logoffs. if (logOffRequestTime != DateTime.MinValue && logOffRequestTime.AddSeconds(6) <= DateTime.UtcNow) { SendFinalLogOffMessages(); } }
/// <summary> /// This is run in parallel from our main loop. /// </summary> public void Update(double lastTick, long currentTimeTick) { // Checks if the session has stopped responding. if (currentTimeTick >= Network.TimeoutTick) { // Change the state to show that the Session has reached a timeout. State = SessionState.NetworkTimeout; } Network.Update(lastTick); // Live server seemed to take about 6 seconds. 4 seconds is nice because it has smooth animation, and saves the user 2 seconds every logoff // This could be made 0 for instant logoffs. if (logOffRequestTime != DateTime.MinValue && logOffRequestTime.AddSeconds(6) <= DateTime.UtcNow) { logOffRequestTime = DateTime.MinValue; SendFinalLogOffMessages(); } // Check if the player has been booted if (bootSession) { SendFinalBoot(); State = SessionState.NetworkTimeout; } // todo: I'd like to move this to a player Update() function. Mag-nus 2018-08-10 if (Player != null) { // First, we check if the player hasn't been saved in the last 5 minutes if (Player.LastRequestedDatabaseSave + Player.PlayerSaveInterval <= DateTime.UtcNow) { // Secondly, we make sure this session hasn't requested a save in the last 5 minutes. // We do this because EnqueueSaveChain will queue an ActionChain that may not execute immediately. This prevents refiring while a save is pending. if (lastAutoSaveTime + Player.PlayerSaveInterval <= DateTime.UtcNow) { lastAutoSaveTime = DateTime.UtcNow; Player.EnqueueSaveChain(); } } if (lastAgeIntUpdateTime == DateTime.MinValue) { lastAgeIntUpdateTime = DateTime.UtcNow; } if (lastAgeIntUpdateTime != DateTime.MinValue && lastAgeIntUpdateTime.AddSeconds(1) <= DateTime.UtcNow) { Player.UpdateAge(); lastAgeIntUpdateTime = DateTime.UtcNow; } if (lastSendAgeIntUpdateTime == DateTime.MinValue) { lastSendAgeIntUpdateTime = DateTime.UtcNow; } if (lastSendAgeIntUpdateTime != DateTime.MinValue && lastSendAgeIntUpdateTime.AddSeconds(7) <= DateTime.UtcNow) { Player.SendAgeInt(); lastSendAgeIntUpdateTime = DateTime.UtcNow; } } }
void Update() { net.Update(); }
protected override void Update(GameTime time) { Performance.UpdateFPS.Record(1 / time.ElapsedGameTime.TotalSeconds); Timers.Update(time); Globe.IsActive = IsActive; Mouse.Update(); Keyboard.Update(time); XboxPad.Update(time); if (XboxPad.Pressed(XboxPad.Buttons.Back) || Keyboard.Pressed(Keyboard.Keys.Escape) || Quit) { Exit(); } if (Keyboard.Pressed(Keyboard.Keys.F3)) { Profiler.Enabled = !Profiler.Enabled; } Profiler.Start("Game Update"); #region Menu/Connecting if (Frame == Frames.Menu) { UpdateMenuWorld(time); if (MenuState == MenuStates.UsernameEntry) { if (IsActive) { BlinkTimer -= time.ElapsedGameTime.TotalSeconds; if (BlinkTimer <= 0) { BlinkTimer += .6; } var name = Settings.Get("Name").AcceptInput(String.InputFlags.NoLeadingSpaces | String.InputFlags.NoRepeatingSpaces, 20); Settings.Set("Name", name); if (Keyboard.Pressed(Keyboard.Keys.Enter) && !name.IsNullOrEmpty()) { MenuState = MenuStates.HostConnect; } } } else if (MenuState == MenuStates.HostConnect) { if (Mouse.Press(Mouse.Buttons.Left)) { Vector2 scale = Scale * .75f, size = _orbisFont.MeasureString("Host") * scale; var button = new Rectangle((int)(Screen.BackBufferWidth / 2f - size.X / 2f), (int)(Screen.BackBufferHeight / 2f - size.Y), (int)size.X, (int)size.Y); if (new Rectangle(Mouse.X, Mouse.Y, 1, 1).Intersects(button)) { Multiplayer.CreateLobby(Settings.Get("Name")); GenStarted = false; Frame = Frames.LoadGame; } scale = Scale * .75f; size = _orbisFont.MeasureString("Connect") * scale; button = new Rectangle((int)(Screen.BackBufferWidth / 2f - size.X / 2f), (int)(Screen.BackBufferHeight / 2f + size.Y * .25f), (int)size.X, (int)size.Y); if (new Rectangle(Mouse.X, Mouse.Y, 1, 1).Intersects(button)) { MenuState = MenuStates.IPEntry; } } } else if (MenuState == MenuStates.IPEntry) { if (IsActive) { BlinkTimer -= time.ElapsedGameTime.TotalSeconds; if (BlinkTimer <= 0) { BlinkTimer += .6; } var ip = Settings.Get("IP").AcceptInput( String.InputFlags.NoLeadingPeriods | String.InputFlags.NoLetters | String.InputFlags.NoSpecalCharacters | String.InputFlags.NoSpaces | String.InputFlags.AllowPeriods | String.InputFlags.NoRepeatingPeriods | String.InputFlags.AllowColons | String.InputFlags.NoRepeatingColons | String.InputFlags.NoLeadingPeriods, 21); Settings.Set("IP", ip); if (Keyboard.Pressed(Keyboard.Keys.Enter) && !ip.IsNullOrEmpty()) { Network.Connect(Settings.Get("IP").Split(':')[0], Settings.Get("IP").Contains(":") ? Convert.ToInt32(Settings.Get("IP").Split(':')[1]) : Multiplayer.Port, new Network.Packet(null, Settings.Get("Name"))); Frame = Frames.Connecting; } else if (Keyboard.Pressed(Keyboard.Keys.Tab)) { MenuState = MenuStates.HostConnect; } } } Network.Update(); } else if (Frame == Frames.Connecting) { UpdateMenuWorld(time); BlinkTimer -= time.ElapsedGameTime.TotalSeconds; if (BlinkTimer <= 0) { BlinkTimer += 1; } Network.Update(); } #endregion #region LoadGame/Game else if (Frame == Frames.LoadGame) { UpdateMenuWorld(time); BlinkTimer -= time.ElapsedGameTime.TotalSeconds; if (BlinkTimer <= 0) { BlinkTimer += 1; } if (Network.IsNullOrServer) { if (!GenStarted) { LoadingText = null; GenDone = false; var thread = new Thread(() => { GameWorld = World.Generate(8400, 2400); }) { IsBackground = true }; thread.Start(); GenStarted = true; } if (GenDone) { BufferedStrings = new OrderedDictionary(); if (MenuMusicChannel.HasValue) { Sound.Terminate(MenuMusicChannel.Value); MenuMusicChannel = null; } LoadItems(); Self.Spawn(GameWorld.Spawn); GameWorld.Position = Self.WorldPosition; Frame = Frames.Game; } } Network.Update(); } else if (Frame == Frames.Game) { MouseTileX = (int)Math.Floor(Mouse.CameraPosition.X / Tile.Size); MouseTileY = (int)Math.Floor(Mouse.CameraPosition.Y / Tile.Size); Self.SelfUpdate(time); foreach (var t in Players) { t?.Update(time); } GameWorld.Position = Self.WorldPosition; if (Settings.IsDebugMode) { if (Keyboard.Pressed(Keyboard.Keys.L)) { GameWorld.Light = !GameWorld.Light; } if (Mouse.ScrolledUp()) { GameWorld.Zoom = MathHelper.Min(8, (float)Math.Round(GameWorld.Zoom + ZoomRate, 2)); } if (Mouse.ScrolledDown()) { GameWorld.Zoom = MathHelper.Max(.5f, (float)Math.Round(GameWorld.Zoom - ZoomRate, 2)); } if (Keyboard.Pressed(Keyboard.Keys.D1)) { Self.AddItem(Items["Dirt"].Clone(Keyboard.HoldingShift() ? 30 : 3)); } if (Keyboard.Pressed(Keyboard.Keys.D2)) { Self.AddItem(Items["Stone"].Clone(Keyboard.HoldingShift() ? 30 : 3)); } } for (var i = (BufferedStrings.Count - 1); i >= 0; i--) { var bString = (BufferedStrings[i] as BufferedString); bString.CalculateRectangle(_orbisFont, new Vector2(Self.WorldPosition.X, (Self.WorldPosition.Y - BufferedString.PlayerYOffset))); if (i < (BufferedStrings.Count - 1)) { if (bString.Rectangle.Intersects((BufferedStrings[i + 1] as BufferedString).Rectangle)) { bString.Offset -= (20 * (float)time.ElapsedGameTime.TotalSeconds); } else { bString.Offset += (20 * (float)time.ElapsedGameTime.TotalSeconds); } } else { bString.Offset = MathHelper.Min(0, (bString.Offset + (20 * (float)time.ElapsedGameTime.TotalSeconds))); } bString.Life -= (float)time.ElapsedGameTime.TotalSeconds; if (bString.Life <= 0) { BufferedStrings.RemoveAt(i); i--; } } Network.Update(); } #endregion Profiler.Stop("Game Update"); Textures.Dispose(); Sound.AutoTerminate(); base.Update(time); }
public void Close() { Network.SetState(NetworkClient.ConnectionState.Closed); Network.Update(); Network.Destroy(); }