Search code examples
c#.netarrayspacketbytebuffer

How to properly write a UDP packet


I am trying to rewrite some of my code from a C++ program I wrote a while ago, but I am not sure if/how I can write to a byte array properly, or if I should be using something else. The code I am trying to change to C# .NET is below.

unsigned char pData[1400];
bf_write g_ReplyInfo("SVC_ReplyInfo", &pData, 1400);

void PlayerManager::BuildReplyInfo()
{   
    // Delete the old packet
    g_ReplyInfo.Reset();

    g_ReplyInfo.WriteLong(-1);
    g_ReplyInfo.WriteByte(73);
    g_ReplyInfo.WriteByte(g_ProtocolVersion.GetInt());
    g_ReplyInfo.WriteString(iserver->GetName());
    g_ReplyInfo.WriteString(iserver->GetMapName());
}

Solution

  • BinaryWriter might work, although strings are written with a preceding 7-bit encoded length, which I suspect the client won't be able to handle. You'll probably have to convert strings to bytes and then either add a length word or 0-terminate it.

    No need to manually convert numbers to bytes. If you have a long that you want to write as a byte, just cast it. That is, if your BinaryWriter is bw, then you can write bw.Write((byte)longval);. To write -1 as a long: bw.Write((long)(-1)).