I have a server that can send commands to the Unity application. I’m using long polling. I create delayed POST requests and await for server response for up to one minute. When server has some command, it responds with this command. If there are no commands - the request is getting timed out and a new one is sent.
The server accepts POST requests with raw json in the body.
Here is my code using WWW:
void getServerCommand()
{
Dictionary<string, object> data = new Dictionary<string, object>();
data.Add("command", "getServerCommand");
data.Add("gatewayId", gatewayId);
data.Add("timeout", cloudCommandTimeoutDuration);
string jsonString = JsonConvert.SerializeObject(data);
byte[] body = Encoding.UTF8.GetBytes(jsonString);
Dictionary<string,string> headers = new Dictionary<string, string>();
headers.Add("Content-Type", "application/json");
WWW www = new WWW(cloudUrl, body, headers);
StartCoroutine(WaitForCommand(www));
}
IEnumerator WaitForCommand(WWW www)
{
yield return www;
if (www.isDone)
{
Debug.Log("Command accepted.");
}
else
{
Debug.Log("WWW Error: " + www.error + ", body:" + www.text);
}
processResponse(www.text);
}
I’m trying to upgrade to UnityWebRequest and this is what I have right now:
IEnumerator Post(string url, string bodyJsonString)
{
var request = new UnityWebRequest(url, "POST");
byte[] bodyRaw = Encoding.UTF8.GetBytes(bodyJsonString);
request.uploadHandler = new UploadHandlerRaw(bodyRaw);
request.downloadHandler = new DownloadHandlerBuffer();
request.uploadHandler.contentType = "application/json";
yield return request.SendWebRequest();
Debug.Log("Status Code: " + request.responseCode);
request.Dispose();
doSendNewRequest = true;
}
But this returns Status Code: 409 instead of waiting for the response from the server.
Is it possible to do long polling with UnityWebRequest?