我如何在Unity和aws lambda函数之间进行通信?

时间:2019-02-14 11:45:31

标签: c# unity3d aws-lambda

我在Unity上有一个工作UnityWebRequest ...

private static void SendMessageToServerless(MessageBase message) {
    string uri = "https://urigoeshere.com/test";

    Get(uri, message);
}

private static void Get(string uri, MessageBase message) {
    instance.StartCoroutine(GetRequest(uri, message));
}

private static IEnumerator GetRequest(string uri, MessageBase message) {
    // TODO: Do something with message
    UnityWebRequest webRequest = UnityWebRequest.Get(uri);
    yield return webRequest.SendWebRequest();

    Debug.Log(webRequest.downloadHandler.text);
}

...而且我分别在AWS上有一个可用的C#lambda ...

[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
namespace SwordPlayServerless {
    public class Function {
        public string FunctionHandler(string input, ILambdaContext context) {
            return "Hello " + input;
        }
    }
}

...但是我不确定如何弥合差距以及将键入内容从一个发送到另一个。我通常会收到以下错误消息作为答复:

{
  "errorType": "JsonSerializerException",
  "errorMessage": "Error converting the Lambda event JSON payload to a string. JSON strings must be quoted, for example \"Hello World\" in order to be converted to a string: Unexpected character encountered while parsing value: {. Path '', line 1, position 1.",
  ...

1 个答案:

答案 0 :(得分:0)

发送json-data时,您需要设置lambda函数以期望JObject作为输入。然后,您可以将json转换为任何合适的对象入站或出站:

using Newtonsoft.Json.Linq;

public JObject FunctionHandler(JObject jsonContent, ILambdaContext context) {
    Message clientMessage = jsonContent.ToObject<Message>();
    // ...
    Message response = new Message();
    return JObject.FromObject(response);
}

Unity内置了对JSON的支持。我的原始代码已关闭...

private static void SendMessageToServerless(Message message) {
    string uri = "https://example.com/test";

    instance.StartCoroutine(SendMessageToServerlessAsync(uri, message));
}

private static IEnumerator SendMessageToServerlessAsync(string uri, Message message) {
    UnityWebRequest webRequest = UnityWebRequest.Put(uri, JsonUtility.ToJson(message));
    yield return webRequest.SendWebRequest();

    if (webRequest.isNetworkError) {
        Debug.LogError("Network error: " + webRequest.error);
    } else { 
        Message response = JsonUtility.FromJson<Message>(webRequest.downloadHandler.text);
        Debug.Log(response.statusCode);
    }
}

通过这种方式,服务器和客户端都可以为Message类使用相同的定义,只要它是可序列化的即可。