简体   繁体   English

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

[英]XNA and Lidgren Error: Trying to read past buffer size?

I am trying to create an online game using XNA and the Lidgren Networking Library. 我正在尝试使用XNA和Lidgren Networking Library创建一个在线游戏。 However, right now I am having trouble sending and receiving any messages without getting the error: "Trying to read past the buffer size - likely caused by mismatching Write/Reads, different size or order." 但是,现在我在发送和接收任何消息时都遇到麻烦,而没有得到以下错误: “试图读取缓冲区大小,这可能是由于写入/读取,大小或顺序不匹配导致的。”

I send the messages to the client like this: 我像这样将消息发送给客户端:

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.");
}

Where PacketTypes.Start is part of an enum set up to distinguish between different messages. 其中PacketTypes.Start是枚举设置的一部分,用于区分不同的消息。

The client receives this message like so: 客户端收到此消息,如下所示:

    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;

        }
    }
}

But no matter what I've tried, I still get that error. 但是,无论我尝试了什么,我仍然会收到该错误。 Please, any help will be appreciated. 请任何帮助将不胜感激。

You only write one byte to your packets when you send them: 发送数据包时,您只需向其写入一个字节:

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

But read two when you receive them: 但是,收到它们时请阅读以下两项:

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

Edit 编辑

To resolve the issue change your code to this: 要解决此问题,请将您的代码更改为此:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM