2

所以我有一个预建的服务器,专为我的班级(学校班级,而不是代码)设计,我知道它可以工作,因为其他人可以使用它。

我正在尝试使用 UnityWebRequest 将 JSON 字符串发送到服务器,但它似乎没有发送。服务器正在监听 127.0.0.1:8000,我在 Unity 中使用了 URL“ http://127.0.0.1:8000 ”。

public class NetworkTest : MonoBehaviour

{
  void Start()
  {
    string url = "http://127.0.0.1:8000";
    Base message = new Base();
    Data data = new Data();
    Configuration conf = new Configuration();

    message.messageType = "connect";
    data.game = "default";
    data.clientType = "client";
    conf.id = "test";
    data.configuration = conf;
    message.data = data;

    string json = JsonUtility.ToJson(message);
    Debug.Log("Json: " + json);
    StartCoroutine(Post(url, json));
  }

  IEnumerator Post(string url, string bodyJsonString)
  {
    var request = new UnityWebRequest(url, "POST");
    byte[] bodyRaw = Encoding.UTF8.GetBytes(bodyJsonString);
    request.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw);
    request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
    request.SetRequestHeader("Content-Type", "application/json");
    request.timeout = 20;

    yield return request.SendWebRequest();
    Debug.Log(request.downloadHandler.data);
    Debug.Log("after sendrequest");

    Debug.Log("Status Code: " + request.responseCode);
  }


}

代码运行良好,但我每次都得到 Status Code: 0 。有人可以帮我吗?

4

0 回答 0