在Xna中读取和发送数据包

时间:2013-10-23 08:58:18

标签: c# xna

这是我的代码:

//Code for host
case (GameState.PlayingAsHost):
{
  session.Update();

  while (session.LocalGamers[0].IsDataAvailable) //Recieve data
  {
     NetworkGamer sender;
     PacketReader reader = new PacketReader();

     session.LocalGamers[0].ReceiveData(reader, out sender);

     guestPaddle.Position = reader.ReadVector2();
  }

  hostPaddle.Update(); //Update paddle position

  var packetWriter = new PacketWriter(); //Send data
  packetWriter.Write(new Vector2(hostPaddle.Position.X, 50));
  session.LocalGamers[0].SendData(packetWriter,SendDataOptions.InOrder);

  break;
}

//Guest Code
case (GameState.PlayingAsGuest):
{
  session.Update();

  while (session.LocalGamers[0].IsDataAvailable)//Recieve data
  {
     NetworkGamer sender;
     PacketReader reader = new PacketReader();

     session.LocalGamers[0].ReceiveData(reader, out sender);

     hostPaddle.Position = reader.ReadVector2();
  }

  guestPaddle.Update(); //Update paddle position

  var packetWriter = new PacketWriter(); //Send data
  packetWriter.Write(new Vector2(guestPaddle.Position.X, 50));
  session.LocalGamers[0].SendData(packetWriter, SendDataOptions.InOrder);

  break;
}

这将是一个乒乓球多人游戏(因此是桨名)。 之前,当客人在接收之前发送了它的包裹时,代码工作除了当作为客人玩时,主持人的X位置被设置为客人的X位置。我正在测试是否更改,以便客户端和主机在发送之前收到数据将解决问题。通过这样做,主机收到错误消息:“无法读取超出流的末尾”。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我认为您的switch and case只是因为could be a more efficient方式而不是if

为了重现if的行为,您需要在案例中放置break或将其包含在括号中。我不确定你是否意识到这一点,或者问题是否存在,但你的括号似乎肯定搞砸了,因为你的客座案在你的主机案件中。

//Code for host
case (GameState.PlayingAsHost):
{
  session.Update();

  while (session.LocalGamers[0].IsDataAvailable) //Recieve data
  {
     NetworkGamer sender;
     PacketReader reader = new PacketReader();

     session.LocalGamers[0].ReceiveData(reader, out sender);

     guestPaddle.Position = reader.ReadVector2();
  }

  hostPaddle.Update();

  var packetWriter = new PacketWriter(); //Send data
  packetWriter.Write(new Vector2(hostPaddle.Position.X, 50));
  session.LocalGamers[0].SendData(packetWriter,SendDataOptions.InOrder);
}

//Guest Code
case (GameState.PlayingAsGuest):
{
  session.Update();

  while (session.LocalGamers[0].IsDataAvailable)//Recieve data
  {
     NetworkGamer sender;
     PacketReader reader = new PacketReader();

     session.LocalGamers[0].ReceiveData(reader, out sender);

     hostPaddle.Position = reader.ReadVector2();
  }

  guestPaddle.Update();

  var packetWriter = new PacketWriter(); //Send data
  packetWriter.Write(new Vector2(guestPaddle.Position.X, 50));
  session.LocalGamers[0].SendData(packetWriter, SendDataOptions.InOrder);
}

这应该有效,我不确定方法中有什么,所以你可能不得不将*paddle.Update()移出案例。