Windsmith
HTTP Streams don't stream data for me
I'm working with an api that streams data.
I want to do some tasks on the data as it is coming and I'm using the GetStreamAsync method of the HTTPClient.
But the program always waits for the entire data to come and the stream to end before showing the output.
C#
public async void streamGame()
{
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "apiToken");
Debug.Log("Starting");
string json = "";
int count = 0;
using (Stream response = await client.GetStreamAsync($"https://lichess.org/api/board/game/stream/gHsBvpVYMuur"))
{
var line = new List<char>();
while (true)
{
var nextByte = response.ReadByte();
if (nextByte == -1)
{
break;
}
line.Add(Char.ConvertFromUtf32(nextByte)[0]);
if (nextByte == '\n')
{
json += string.Join("", line);
Debug.Log(json);
count++;
gameId.text = count.ToString();
line.Clear();
if (json.Length == 1)
{
continue;
}
}
}
Debug.Log(json);
Debug.Log("Finished");
}
}
C#
public async void streamGame()
{
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "apiToken");
Debug.Log("Starting");
string json = "";
int count = 0;
using (Stream response = await client.GetStreamAsync($"https://lichess.org/api/board/game/stream/gHsBvpVYMuur"))
{
var line = new List<char>();
while (true)
{
var nextByte = response.ReadByte();
if (nextByte == -1)
{
break;
}
line.Add(Char.ConvertFromUtf32(nextByte)[0]);
if (nextByte == '\n')
{
json += string.Join("", line);
Debug.Log(json);
count++;
gameId.text = count.ToString();
line.Clear();
if (json.Length == 1)
{
continue;
}
}
}
Debug.Log(json);
Debug.Log("Finished");
}
}
1 replies