2017-02-09 5 views
0

입니다. 그래서 지금은 서버에 HTTP 요청을하고 있지만 일부 JSON 데이터와 함께 GET 요청을 보내야합니다. 내가 지금하고있는 일은 "일"하지만, 각 요청이 거의 15FPS까지 떨어지기 때문에 끔찍한 일이다. 여기 내 코드가있다.Unity에서 서버에 GET 요청을하는 가장 좋은 방법은

private IEnumerator SetJsonData() 
{ 
    // Make a new web request with the .net WebRequest 
    request = WebRequest.Create(elk_url); 
    yield return null; 

    request.ContentType = "application/json"; 
    request.Method = "POST"; 
    buffer = Encoding.GetEncoding("UTF-8").GetBytes(queryString); 

    // Put this yield here so that I get higher FPS 
    yield return null; 

    requestStream = request.GetRequestStream(); 
    requestStream.Write(buffer, 0, buffer.Length); 
    requestStream.Close(); 
    // Again this is about getting higher FPS 
    yield return null; 

    response = (HttpWebResponse)request.GetResponse(); 
    // Wait until we have all of the data we need from the response to continue 
    yield return requestStream = response.GetResponseStream(); 

    // Open the stream using a StreamReader for easy access. 
    reader = new StreamReader(requestStream); 
    // Set my string to the response from the website 
    JSON_String = reader.ReadToEnd(); 

    yield return null; 

    // Cleanup the streams and the response. 
    reader.Close(); 
    requestStream.Close(); 
    response.Close(); 
    yield return null; 

    // As long as we are not null, put this in as real C# data 
    if (JSON_String != null) 
    { 
     // Wait until we finish converting the string to JSON data to continue 
     yield return StartCoroutine(StringToJson()); 
    } 

    if(dataObject != null) 
    { 
     // Send the data to the game controller for all of our hits 
     for(int i = 0; i < dataObject.hits.hits.Length; i++) 
     { 
      StartCoroutine(
       gameControllerObj.CheckIpEnum(dataObject.hits.hits[i]._source)); 
     } 
    } 

    // As long as we didn't say to stop yet 
    if (keepGoing) 
    { 
     yield return null; 

     // Start this again 
     StartCoroutine(SetJsonData()); 
    } 
} 
: 실제로 요청을 할 내가 설정 한 공동 coutine 여기

void Start() 
{ 
     queryString = File.ReadAllText(Application.streamingAssetsPath +"/gimmeData.json"); 

     StartCoroutine(SetJsonData()); 
} 

됩니다 : 여기

{ 
"query": { 
    "match_all": {} 
}, 
"size": 1, 
"sort": [{ 
    "@timestamp": { 
     "order": "desc" 
    } 
}] 
} 

내 시작 방법 : 여기

내 GET 쿼리입니다

FPS가 이미 개선 된 때문에 "수익률 반환 null"이 있습니다.

어떻게 최적화 할 수 있습니까? 거기에 GET 데이터를 보낼 수있는 웹 요청을 만드는 더 좋은 방법이 있습니까? UnityWebRequest가 문제라는 것을 알고 있습니다. 그렇다고해서 제가 가지고있는 JSON 데이터를 보낼 수는 없습니다.

답변

2

참고 : 질문의 코드는 GET이 아닌 POST를 수행하고 있습니다. '데이터 가져 오기'와 같은 것은 없습니다.

다음 제안은 서버의 관점과 동일합니다.

실제로 GET 요청 (코드가하는 것과 완전히 다른 것)을 원한다면이 답변의 끝 부분을 참조하십시오.

코 루틴은 스레드

Wait until we have all of the data하지 않습니다 - 당신의 프레임 속도가 죽을 오는 곳입니다. 이는 Unity 메인 스레드 (본질적으로 전체 게임)가 서버가 모든 데이터로 응답 할 때까지 기다릴 것이기 때문입니다.

간단히 말해 코 루틴의 작동 방식 때문입니다. 스레드와 매우 다릅니다.

Unity의 일반적인 접근법은 코 루틴에서 WWW을 대신 사용하는 것입니다. 내부적으로 단결은 별도의 스레드에서 실제 요청을 실행하고 코 루틴은 단지 모든 너무 자주 진행 상황의 확인 : 귀하의 질문에 일치하는

// Build up the headers: 
Dictionary<string,string> headers = new Dictionary<string,string>(); 

// Add in content type: 
headers["Content-Type"] = "application/json"; 

// Get the post data: 
byte[] postData = Encoding.GetEncoding("UTF-8").GetBytes(queryString); 

// Start up the reqest: 
WWW myRequest = new WWW(elk_url, postData, headers); 

// Yield until it's done: 
yield return myRequest; 

// Get the response (into your JSON_String field like above) 
// Don't forget to also check myRequest.error too. 
JSON_String = myRequest.text; 

// Load the JSON as an object and do magical things next. 
// There's no need to add extra yields because 
// your JSON parser probably doesn't support chunked json anyway.   
// They can cover a few hundred kb of JSON in an unnoticeable amount of time. 
.... 

GET : 질문의 코드와 일치,

POST :

// Start up the reqest (Total guess based on your variable names): 
// E.g. mysite.com/hello?id=2&test=hi 
WWW myRequest = new WWW(elk_url + "?"+queryString); 

// Yield until it's done: 
yield return myRequest; 

// Get the response 
JSON_String = myRequest.text; 
.... 
관련 문제