WX-Game1/Assets/Scripts/MessageHandler.cs

87 lines
2.5 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 System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LitJson;
/// <summary>
/// 接收来自网页的消息
/// </summary>
public class MessageHandler : MonoBehaviour
{
/// <summary>
/// JSON消息数据结构类
/// 用于解析来自网页的JSON消息
/// </summary>
[System.Serializable]
public class MessageData
{
/// <summary>
/// 消息代码
/// </summary>
public string code;
}
/// <summary>
/// 接收来自网页的消息
/// </summary>
/// <param name="message">来自网页的消息字符串</param>
public void ReceiveMessageFromWeb(string message)
{
// 打印原始消息到控制台
Debug.Log($"收到来自网页的消息: {message}");
// 尝试解析JSON消息
ParseJsonMessage(message);
}
/// <summary>
/// 解析JSON消息
/// </summary>
/// <param name="jsonMessage">JSON格式的消息字符串</param>
private void ParseJsonMessage(string jsonMessage)
{
try
{
// 使用LitJson解析JSON消息
MessageData messageData = JsonMapper.ToObject<MessageData>(jsonMessage);
// 打印解析后的消息数据
Debug.Log($"成功解析JSON消息 - 代码: {messageData.code}");
// 处理解析后的消息数据
HandleParsedMessage(messageData);
}
catch (System.Exception ex)
{
// 如果JSON解析失败记录错误信息
Debug.LogError($"JSON解析失败: {ex.Message}");
Debug.LogError($"原始消息内容: {jsonMessage}");
}
}
/// <summary>
/// 处理解析后的消息数据
/// </summary>
/// <param name="messageData">解析后的消息数据</param>
private void HandleParsedMessage(MessageData messageData)
{
// 根据消息代码执行相应的处理逻辑
Debug.Log($"正在处理消息代码: {messageData.code}");
// 这里可以添加具体的业务逻辑处理
// 例如根据不同的code值执行不同的操作
switch (messageData.code)
{
case "1234":
Debug.Log("检测到特定代码1234执行相应操作");
// 在这里添加具体的业务逻辑
break;
default:
Debug.Log($"收到未知代码: {messageData.code}");
break;
}
}
}