将枚举转换为字节并将它们发送给 lidgren

Casting enums to bytes and sending them lidgren

我有这个接收消息的代码:

private void DataMessage(NetIncomingMessage msg)
{
    NetOutgoingMessage outmsg = server.CreateMessage();
    DataType data = (DataType)msg.ReadByte();
    switch (data)
    {
        case DataType.DATATYPEMSG:
            string s = msg.ReadString();
            Console.WriteLine(s);
            outmsg.Write(s);
            outmsg.Write((byte)DataType.DATATYPEMSG);
            server.SendToAll(outmsg,NetDeliveryMethod.ReliableUnordered);
            break;
        case DataType.DATATYPEOTHER:
            outmsg.Write((byte)DataType.DATATYPEMSG);
            outmsg.Write("please try this again later");
            server.SendMessage(outmsg,msg.SenderConnection,NetDeliveryMethod.ReliableUnordered);
                break;
        case DataType.DATATYPEREQUEST:
            break;
        default: msg.SenderConnection.Disconnect("if you believe you where wrongly picked up for editing the code please contact the developer");
            break;
    }
}

以及用于发送它们的代码:

internal void sendmsg(string v)
{
    NetOutgoingMessage outmsg = tclient.CreateMessage(v);
    outmsg.Write((byte)DataType.DATATYPEMSG);
    tclient.SendMessage(outmsg, NetDeliveryMethod.ReliableUnordered);
}

如果消息到达服务器,它只会调用默认值并断开用户连接。

当您创建消息时,您在 DataType 之前写入消息文本,但是当您收到消息时,您希望 DataType 出现在文本之前。

你可以通过在文本前写DataType来修复它,像这样:

internal void sendmsg(string v)
{
    NetOutgoingMessage outmsg = tclient.CreateMessage();
    outmsg.Write((byte)DataType.DATATYPEMSG);
    outmsg.Write(v);
    tclient.SendMessage(outmsg, NetDeliveryMethod.ReliableUnordered);
}

我变了 NetOutgoingMessage outmsg = server.CreateMessage(); DataType data = (DataType)msg.ReadByte(); switch (data) { case DataType.DATATYPEMSG: string s = msg.ReadString(); 到: NetOutgoingMessage outmsg = server.CreateMessage(); DataType data = (DataType)msg.ReadByte(); string s = msg.ReadString();