質問

I am trying to create an online game using XNA and the 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.

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帰属
所属していません StackOverflow
scroll top