XNA和Lidgren错误:试图读取过去的缓冲区大小?

时间:2013-07-10 15:38:28

标签: networking xna lidgren

我正在尝试使用XNA和Lidgren Networking Library创建一个在线游戏。但是,现在我在发送和接收任何消息时遇到问题而没有收到错误:“尝试读取超过缓冲区大小 - 可能是由于写入/读取不匹配,大小或顺序不同造成的。”

我将消息发送到客户端,如下所示:

if (btnStart.isClicked && p1Ready == "Ready")
{
    btnStart.isClicked = false;
    NetOutgoingMessage om = server.CreateMessage();
    CurrentGameState = GameState.City;
    om.Write((byte)PacketTypes.Start);                                    
    server.SendMessage(om, server.Connections, NetDeliveryMethod.Unreliable, 0);
    numPlayers = 2;
    Console.WriteLine("Game started.");
}

其中PacketTypes.Start是枚举的一部分,用于区分不同的消息。

客户端收到此消息,如下所示:

    if (joining)
{
    NetIncomingMessage incMsg;
    while ((incMsg = client.ReadMessage()) != null)
    {
    switch (incMsg.MessageType)
    {


    case NetIncomingMessageType.Data:
    if (incMsg.ReadByte() == (byte)PacketTypes.Ready)
    {
        p1Ready = "Ready";                                                
    }
    else if (incMsg.ReadByte() == (byte)PacketTypes.Start)
    {
        CurrentGameState = GameState.City;
        Console.WriteLine("Game started");
        numPlayers = 2;
    }

    break;

    default:
        Console.WriteLine("Server not found, Retrying...");
    break;

        }
    }
}

但无论我尝试过什么,我仍然会遇到这个错误。请帮助任何帮助。

1 个答案:

答案 0 :(得分:1)

发送时只能在数据包中写入一个字节:

om.Write((byte)PacketTypes.Start);

但是当你收到它们时,请阅读两篇文章:

// One read here
if (incMsg.ReadByte() == (byte)PacketTypes.Ready)
{
    p1Ready = "Ready";                                                
}
// Second read here
else if (incMsg.ReadByte() == (byte)PacketTypes.Start)

修改

要解决此问题,请将代码更改为:

case NetIncomingMessageType.Data:
    byte type = incMsg.ReadByte(); // Read one byte only

    if (type == (byte)PacketTypes.Ready)
    {
        p1Ready = "Ready";                                                
    }
    else if (type == (byte)PacketTypes.Start)
    {
        CurrentGameState = GameState.City;
        Console.WriteLine("Game started");
        numPlayers = 2;
    }

break;