菜鸟教程小白 发表于 2022-12-11 20:13:06

android - 如何在移动设备上使用 UDP 解决高延迟问题


                                            <p><p>我在使用 Unity 制作的多人射击游戏时遇到网络延迟较低的问题。我正在使用 UDP 将玩家位置从游戏客户端发送到我的亚马逊服务器并返回到另一个游戏客户端。我的游戏客户端以每秒 8 个数据包的速率向亚马逊服务器发送 60 字节的 UDP 数据包。</p>

<p>当我在两台不同的 iOS 设备(iPhone 7 和 iPad mini)上玩游戏时,网络延迟非常低,玩家可以立即看到彼此的 Action 。但是,如果我在我的 iPhone 7 上运行游戏并与另一个使用运行 android 的 samsung Galaxy s4 的玩家对战,这是一个低功耗设备,当从 iOS 设备接收玩家位置时,我会在 android 设备上遇到 5 秒延迟.奇怪的是,iOS 设备可以立即从 android 设备接收玩家位置。在 iPhone 7 上与 mac 上的客户端玩游戏时会发生同样的问题,除了 iPhone 7 在从 mac 客户端接收玩家位置时会遇到 5 秒的延迟。在三星 Galaxy S4 上与 Mac 上的客户端玩游戏时也会出现此问题,Galaxy s4 会遇到 5 秒的延迟。</p>

<p>我尝试将 udp 接收缓冲区大小增加到 16 MB,但没有任何改变。</p>

<p>这是我将玩家位置发送到亚马逊服务器的游戏客户端代码示例:</p>

<pre><code>    void Update(){
    // manually constrain rotation because rigidbody constraints don&#39;t work
    this.transform.rotation = Quaternion.Euler(new Vector3(0, this.transform.rotation.eulerAngles.y, 0));
    this.transform.position = new Vector3(this.transform.position.x, boatHeightConstant, this.transform.position.z);


    // Speed Boost Handling
    if(isSpeedBoosting == true){
      tiltFactor = tiltModifier * (VelocityRatio() + 1.0f);
      speedBoostTimer += Time.deltaTime;
    }
    else{
      tiltFactor = VelocityRatio() + 1.0f;
    }
    if(speedBoostTimer &gt;= speedBoostDuration){
      isSpeedBoosting = false;
      speedBoostTimer = 0f;
      endSpeedBoost = true;
    }
    if(endSpeedBoost == true){
      GetComponentInChildren&lt;MainWeapon&gt;().EndFireRateBoost();
      endSpeedBoost = false;
    }

    // Attack Boost Handling
    if(isAttackBoosting == true){
      attackBoostTimer += Time.deltaTime;
    }
    if(attackBoostTimer &gt;= attackBoostDuration){
      isAttackBoosting = false;
      attackBoostTimer = 0f;
      endAttackBoost = true;
    }
    if(endAttackBoost == true){
      GetComponentInChildren&lt;MainWeapon&gt;().ResetDamage();
      GetComponentInChildren&lt;MainWeapon&gt;().ResetHeatUpRate();
      endAttackBoost = false;
    }

    if (GetComponent&lt;InputManager&gt;().GetInputType() == 0 || GetComponent&lt;InputManager&gt;().GetInputType() == 1 )
    {
      if (isSpeedBoosting == true)
      {
            Move(speedModifier);

      }
      else
      {

            Move(1f);
      }


      if (syncTimer &lt;= 0f) {
            syncTimer = networkRefreshRate;
            SyncTransform ();
      } else {
            syncTimer -= Time.deltaTime;
      }

    }
    else
    {
      NetworkMove();

    }


}

/// &lt;summary&gt;
/// This function is constantly called to upload the local player&#39;s position to the server so the server is
/// aware of this player&#39;s movement and can share this local players current position with other players in the game.
/// &lt;/summary&gt;
public void SyncTransform() {

    if (isLocalPlayer == true &amp;&amp; client != null &amp;&amp; client.IsConnected()) {
      client.SendPlayerTransform(SharedData.storage[&#34;userId&#34;], transform.position, transform.rotation, currentLife);
    }
}
</code></pre>

<p>这是我的游戏客户端中 UDP 发送器类的示例:</p>

<pre><code>public void SendPlayerTransform(string playerId, Vector3 position, Quaternion rotation, int currentLife) {

    Message.Writer writer = new Message.Writer(Message.MessageType.PlayerTransform, udpClient, remoteEndPoint);
    // Write the timestamp of this message
    writer.WriteLong(DateTime.UtcNow.Ticks);

    // write the player id
    writer.WriteString(SharedData.storage[&#34;userId&#34;]);

    // write the position vector
    writer.WriteFloatArray(CommonGameFunctions.ConvertVectorToFloatArray(position));

    // write the rotation vector
    writer.WriteFloatArray(CommonGameFunctions.ConvertQuaternionToFloatArray(rotation));

    writer.WriteInt (currentLife);

    // Now send the message
    writer.Send();

}
</code></pre>

<p>这是我在游戏客户端接收 UDP 消息的示例:</p>

<pre><code>public int HandleUdpMessages() {
    if (udpTimerStarted == false) {
      lastUdpMessageReceivedTime = DateTime.Now;
      udpTimerStarted = true;
    } else if (udpTimerStarted == true &amp;&amp; udpClient.Available == 0){
      TimeSpan t = DateTime.Now - lastUdpMessageReceivedTime;
      if (t.Seconds &gt;= 10f) {
            // no message received for last 10 seconds then throw IO exception
            //throw new SocketException();
      }
    }

    if (udpClient.Available &gt; 0) {
      var messageReader = new Message.Reader (udpClient);
      messageReader.BlockingRead (ref localEndPoint, UdpReceiveTimeout);
      var messageType = messageReader.ReadMessageTypeUdp ();

      lastUdpMessageReceivedTime = DateTime.Now;
      Debug.Log (&#34;Received udp message: &#34; + messageType);

      switch (messageType) {

      // Player position update message
      case Message.MessageType.PlayerTransform:
            HandlePlayerTransform (messageReader);
            break;
      case Message.MessageType.PlayerScore:
            HandlePlayerScore (messageReader);
            break;
      case Message.MessageType.RockHealth:
            HandleRockHealth (messageReader);
            break;
      case Message.MessageType.PlayerHealth:
            HandlePlayerHealth (messageReader);
            break;
      case Message.MessageType.ShieldHealth:
            HandleShieldHealth (messageReader);
            break;
      default:
            Debug.LogError (&#34;Unhandled message &#34; + messageType);
            break;

      }

    }

    return 0;

}
public void HandlePlayerTransform(Message.Reader reader)
{

    long timeStamp = reader.ReadLong ();
    string playerId = reader.ReadString();

    if (playerMessageTimeStamps .latestPlayerTransform &gt; timeStamp)
      return;

    Vector3 position = new Vector3();
    Quaternion rotation = new Quaternion();

    // read position
    position = CommonGameFunctions.ConvertFloatArrayToVector3(reader.ReadFloatArray(3));

    rotation = CommonGameFunctions.ConvertFloatArrayToQuaternion(reader.ReadFloatArray(4));


    // Now update the transform of the right player

    Player player = Player.playerTable;

    if (player == null) {
      return;
    }

    player.SetNetworkPostion(position);
    player.SetNetworkRotation(rotation);
}
</code></pre>

<p>在我的服务器上,这是在自己的专用线程上运行的主游戏循环。 </p>

<pre><code>    // Now all the players are connected to the server
    // We can start the main game loop
    while (gameRunning == true) {

      HandlePlayersWhoDroppedOut ();

      if (PlayersLeftGame () == true) {
            DisconnectAllPlayers ();
            Debug.LogError (&#34;Player&#39;s left match, returning from thread&#34;);
            return;
      } else {
            foreach (NetworkPlayer p in participants) {

                try {
                  p.HandleTcpMessages ();
                  p.HandleUdpMessages ();
                } catch (IOException e) {
                  droppedPlayers.Add (p);
                }
            }

            try {
                RespawnRocksIfDestroyed ();
            } catch (System.IO.IOException e) {
                DisconnectAllPlayers ();
                return;
                Debug.LogError (&#34;Failed to spawn rocks&#34;);
            }
      }
    }
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>我的代码的问题在于,在 UDP 消息处理函数的每次迭代中,我只读取了一条 UDP 消息。我更改了函数以读取缓冲区中所有可用的 UDP 消息,并且延迟减少了 80%。 UDP 消息在缓冲区中排队的速度比消息处理函数重复的速度要快,所以这就是问题发生的原因。</p></p>
                                   
                                                <p style="font-size: 20px;">关于android - 如何在移动设备上使用 UDP 解决高延迟问题,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/50658421/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/50658421/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: android - 如何在移动设备上使用 UDP 解决高延迟问题