chinese_chess/Scripts/Lib/RPHelper.cs

45 lines
1.4 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Godot;
using Godot.Collections;
namespace RPPackage {
public static class RPHelper
{
public static Dictionary SerializeRPMessage(RPMessage message)
{
return message.ToDictionary();
}
public static RPMessage DeserializeRPMessage(Dictionary data)
{
return new RPMessage
{
Type = data.ContainsKey("type") ? (string)data["type"] : null,
Cmd = data.ContainsKey("cmd") ? (string)data["cmd"] : null,
Code = data.ContainsKey("code") ? (string)data["code"] : null,
Uid = data.ContainsKey("uid") ? (string)data["uid"] : null,
Token = data.ContainsKey("token") ? (string)data["token"] : null,
Data = data.ContainsKey("data") ? data["data"].AsGodotDictionary() : null,
};
}
// 假设你有WebSocket通信的实现这里仅展示如何使用上述方法
public static void SendRPMessage(this EventDrivenWebSocket ws, RPMessage message)
{
ws.SendJsonEx(RPHelper.SerializeRPMessage(message));
}
public static RPMessage HandleIncomingMessage(string jsonMessage)
{
var dataDict = Json.ParseString(jsonMessage).AsGodotDictionary();
if (dataDict != null)
{
return RPHelper.DeserializeRPMessage(dataDict);
}
else
{
GD.PrintErr("Failed to parse incoming message.");
return null;
}
}
}
}